冒泡排序:
package arrays;
public class Sort {
public static void main(String[] args) {
// TODO 自动生成的方法存根
//冒泡排序
int[] array = { 63,4,24,1,3,15};
Sort sorter = new Sort();
sorter.sort(array);
}
public int sort(int[] array) {
for(int i = 1; i < array.length; i++) {
for(int j = 0; j < array.length - i; j++) {
if(array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
showArray(array);
return 0;
}
public int showArray(int[] array) {
for(int i: array) {
System.out.print(" > " + i);
}
System.out.print("/n");
return 0;
}
}
直接选择排序
package arrays;
public class SelectSort {
public static void main(String[] args) {
int[] array = { 63,4,24,1,3,15};
SelectSort sorter = new SelectSort();
sorter.sort(array);
}
public void sort(int[] array) {
int index;
for(int i = 1; i < array.length; i++) {
index = 0;
for(int j = 1; j <= array.length - i; j++) {
if( array[j] > array[index]) {
index = j;
}
}
//交换在位置array.length - i 和 index(最大值)上的两个元素
int temp = array[array.length - i];
array[array.length - i] = array[index];
array[index] = temp;
}
showArray(array);
}
public void showArray(int[] array) {
for(int i : array) {
System.out.print(" > " + i);
}
System.out.println();
}
}
原创文章,作者:1402239773,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/274368.html