/** * Created by changqing on 2017/3/5.快排 */public class main { public static void main(String[] args) { int []nums={1,6,6,8,2,2,5,78,8,21,2,124,4}; QuickSort(nums,0,nums.length-1); for (int i = 0; i < nums.length; i++) { System.out.PRintln(nums[i]); } } public static void QuickSort(int []numbers,int left,int right) { if(left>=right) return; int x=numbers[(left+right)/2]; int low=left,high=right; while(low<high) { while(numbers[high]>x) { high--; } while(numbers[low]<x) { low++; } if(low<=high) { int temp=numbers[low]; numbers[low]=numbers[high]; numbers[high]=temp; low++; high--; } } QuickSort(numbers,left,high); QuickSort(numbers,low,right); }}/** * Created by changqing on 2017/3/5. 选择排序 */public class selectSort { public static void main(String[] args) { int []nums={1,6,6,8,2,2,5,78,8,21,2,124,4}; SelectSort(nums); for (int i = 0; i < nums.length; i++) { System.out.println(nums[i]); } } public static void SelectSort(int []nums) { int size=nums.length; for(int i=0;i<size;i++) { int k=i; for(int j=size-1;j>i;j--) { if(nums[j]<nums[k]) k=j; } int temp=nums[i]; nums[i]=nums[k]; nums[k]=temp; } }}import java.util.Arrays;/** * Created by changqing on 2017/3/5.归并排序 */public class MergeSort { public static void merge(int[] a, int low, int mid, int high) { int[] temp = new int[high - low + 1]; int i = low;// 左指针 int j = mid + 1;// 右指针 int k = 0; // 把较小的数先移到新数组中 while (i <= mid && j <= high) { if (a[i] < a[j]) { temp[k++] = a[i++]; } else { temp[k++] = a[j++]; } } // 把左边剩余的数移入数组 while (i <= mid) { temp[k++] = a[i++]; } // 把右边边剩余的数移入数组 while (j <= high) { temp[k++] = a[j++]; } // 把新数组中的数覆盖nums数组 for (int k2 = 0; k2 < temp.length; k2++) { a[k2 + low] = temp[k2]; } } public static void mergeSort(int[] a, int low, int high) { int mid = (low + high) / 2; if (low < high) { // 左边 mergeSort(a, low, mid); // 右边 mergeSort(a, mid + 1, high); // 左右归并 merge(a, low, mid, high); System.out.println(Arrays.toString(a)); } } public static void main(String[] args) { int a[] = { 51, 46, 20, 18, 65, 97, 82, 30, 77, 50 }; mergeSort(a, 0, a.length - 1); System.out.println("排序结果:" + Arrays.toString(a)); }}public class main { public static int sort(int da[], int a) { int len = da.length; int left = 0, right = len - 1; int mid = 0; while (left <= right) { mid = (left + right) / 2; if (a < da[mid]) { right = mid - 1; } else if (a > da[mid]) { left = mid + 1; } else { return mid; } } return -1; } public static void main(String[] args) { int a[] = {1, 2, 6, 87, 456, 899}; int result = sort(a, 899); System.out.println(result); }}
新闻热点
疑难解答