冒泡排序
int[] arr = new int[] { 34, 23, 45, 67, 23, 66, 88, 22, 54, 12 };
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
int temp = arr[j];
if (arr[j] > arr[j + 1]) {
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
for (int i = 0; i < arr.length - 1; i++) {
System.out.print(arr[i] + "\t");
}
快速排序
public static void quickSort(int[] arr, int low, int height) {
int i,j,temp,t;
if (low > height) {
return;
}
i = low;
j = height;
// temp就是基准位
temp = arr[low];
while(i < j) {
// 先看右边,依次往左边递减
while(temp <= arr[j] && i < j) {
j--;
}
// 在看左边,依次往右递增
while(temp >= arr[i] && i < j) {
i++;
}
// 如果满足条件则交换
if(i < j) {
t = arr[j];
arr[j] = arr[i];
arr[i] = t;
}
}
//最后将基准为与i和j相等位置的数字交换
arr[low] = arr[i];
arr[i] = temp;
// 递归调用左半数组
quickSort(arr, low, j-1);
// 递归调用右半数组
quickSort(arr, j+1, height);
}
int[] arr1 = {10,5,2,4,17,62,33,4,20,1,8,9,19};
quickSort(arr1, 0, arr1.length-1);
for (int i = 0; i < arr1.length; i++) {
System.out.print(arr1[i] + "\t");
}
网友评论