/** * @author shenqi * @date 2018/1/10 * 冒泡排序 * 比较相邻的元素。如果第一个比第二个大,就交换他们两个。 * 对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。在这一点,最后的元素应该会是最大的数。 * 针对所有的元素重复以上的步骤,除了最后一个。 * 持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。 */ public static void bubbleSort(int [] numbers){ int temp = 0; int size = numbers.length; for(int i = 0 ;i < size -1 ; i++){ for(int j = 0 ; j < size -1 -i ;j++){ if(numbers[j] > numbers[j+1]){ temp =numbers[j]; numbers[j] = numbers[j+1]; numbers[j+1] = temp; } } } } /** * 快速排序 * 把整个序列看做一个数组,把第零个位置看做中轴,和最后一个比,如果比它小交换,比它大不做任何处理; * 交换了以后再和小的那端比,比它小不交换,比他大交换。这样循环往复; * 一趟排序完成,左边就是比中轴小的,右边就是比中轴大的,然后再用分治法,分别对这两个独立的数组进行排序。 */ public static int getMiddle(int [] numbers ,int low,int high){ //数组的第一个作为中轴 int temp = numbers[low]; while (low < high){ while (low < high && numbers[high] > temp){ high --; } //比中轴小的记录移到低端 numbers[low] = numbers[high]; while (low < high && numbers[low] < temp){ low++; } //比中轴大的记录移到高端 numbers[high] = numbers[low]; } //中轴记录到尾 numbers[low] = temp; return low; } public static void quickSort(int [] numbers, int low ,int high){ if (low < high){ int middle = getMiddle(numbers,low,high); quickSort(numbers,low,middle-1); quickSort(numbers,middle+1,high); } } public static void quick(int [] numbers){ if (numbers.length > 0){ quickSort(numbers,0,numbers.length -1); } }
冒泡排序和快速排序
最新推荐文章于 2023-04-01 00:23:58 发布