package sort; public class MySort { private int[] array; private int length; /** * 构造函数 * @param array */ public MySort(int[] array){ this.array = array; this.length = array.length; } /** * 打印数组中数据 */ public void display(){ for(int i : array){ System.out.print(i+" "); } System.out.println(); } public static void main(String[] args){ int[] array = {77,44,11,23,45,90,43,65,7,89,42,29,28,36,33,25,10,10,33,100}; // int[] array = {77,44,11,23,45,90,43,65,7}; MySort mySort = new MySort(array); System.out.println("排序前的数据为:"); mySort.display(); mySort.quickSort(0,array.length - 1); System.out.println("排序后的数据为:"); mySort.display(); } /** * 冒泡排序 */ private void bobSort() { for(int i = 0 ; i < array.length - 1 ; ++ i ){ for (int j = i + 1 ; j < array.length ; ++j ){ if(array[i] > array[j]){ int t = array[i]; array[i] = array[j]; array[j] = t; } } } } /** * 选择排序 */ private void selectSort() { for (int i = 0; i < array.length - 1; ++i) { int minIndex = i; for (int j = i + 1; j < array.length; ++j) { if (array[minIndex] > array[j]) { minIndex = j; } } int t = array[i]; array[i] = array[minIndex]; array[minIndex] = t; } } /** * 插入排序 */ private void insertSort(){ for (int i = 1 ; i < array.length ; ++ i){ int temp = array[i]; int leftIndex = i - 1; while ( leftIndex >= 0 && array[leftIndex] > temp ){ array[leftIndex+1] = array[leftIndex]; --leftIndex; } array[leftIndex+1] = temp; } } /** * 快速排序 */ private void quickSort(int low ,int high){ if(low >= high){ return ; } int left = low; int right = high; int temp = array[left]; int t; while (left < right){ //从右往左 while( temp <= array[right] && left < right){ -- right ; } //从左往右 while ( temp >= array[left] && left < right){ ++ left; } if(left < right){ t = array[left]; array[left] = array[right]; array[right] = t; } } array[low] = array[left]; array[left] = temp; quickSort(low,left - 1); quickSort(left + 1,high); } }
Java常见排序,冒泡、选择、插入、快排
最新推荐文章于 2024-07-13 21:40:31 发布