BUBBLE SORT:冒泡排序(每循环一次都把前面最大的放到后面)
存在优化的可能,因为可能前几次排序有可能已经排好序了,接下来的循环已经没必要了,可以设个标志为,看前一次循环是否交换了数据,如果没有,则排序已经好了
package sortprogram; import java.util.*; class BubbleSort { public static void main(String[] args) { int [] a = {10,4,7,9,2,79,66}; bubbleSort(a); System.out.println(Arrays.toString(a)); } public static int[] bubbleSort(int [] a) { int tem = 0;//用来交换时保存数据的 int len = a.length; for(int i = 0; i < len; i++)//根据数组的长度来决定要循环的次数 { for(int j = 1; j < len - i; j++)//比较相邻数据大小,除去了已经排好顺序的 { if(a[j-1] > a[j])//如果前一个大于后一个则交换,将大的放后面 { tem = a[j-1]; a[j-1] = a[j]; a[j] = tem; } } } return a; } }
快速排序:这个看了好多别人写的快速排序算法,有些不太一样貌似存在两种写法的,一种是遍历的时候从左到右,还有的两头开始交叉遍历,但思想好像都是一样的,将选择的标志在数组中插入到中间的位置(前面的都比选的标志小,后面的都比选的标志大)
真是好不容易把程序调试通了,,,,,
https://visualgo.net/en/sorting ----按着这个图的思路来写的代码
1 import java.util.*; 2 3 public class QuickSort 4 { 5 public static void main(String[] args) 6 { 7 System.out.println("Hello World!"); 8 int [] a = {3,44,38,5,47,15,36,26,27,2,46,4,19,50,48}; 9 quickSort(a,0,14); 10 System.out.println(Arrays.toString(a)); 11 } 12 13 public static void quickSort(int []a,int low, int _high) 14 { 15 int pivote =low; 16 int high = _high; 17 int storeIndex = low + 1; 18 int tem = 0; 19 20 System.out.print(low+","+ high + " :" + a[pivote] + ":"); 21 for(int i = low+1; i <= high; i++) 22 { 23 if(a[i] < a[pivote]) 24 { 25 System.out.print(a[i]); 26 tem = a[i]; 27 a[i] = a[storeIndex]; 28 a[storeIndex] = tem; 29 storeIndex++; 30 } 31 32 }
//把pivote的值移动到中间 33 System.out.println(); 34 tem = a[pivote]; 35 a[pivote] = a[storeIndex-1]; 36 a[storeIndex-1] = tem; 37 //System.out.println(low+"," + storeIndex+"," + high); 38 System.out.println(Arrays.toString(a)); 39 if(low < storeIndex-1-1) 40 quickSort(a,low,storeIndex-1-1); 41 if(high > storeIndex) 42 quickSort(a,storeIndex,high); 43 } 44 }
运行结果:包含每次迭代的结果(非常不容易搞通了,,,,)
Hello World! 0,14 :3:2 [2, 3, 38, 5, 47, 15, 36, 26, 27, 44, 46, 4, 19, 50, 48] 2,14 :38:515362627419 [2, 3, 19, 5, 15, 36, 26, 27, 4, 38, 46, 47, 44, 50, 48] 2,8 :19:5154 [2, 3, 4, 5, 15, 19, 26, 27, 36, 38, 46, 47, 44, 50, 48] 2,4 :4: [2, 3, 4, 5, 15, 19, 26, 27, 36, 38, 46, 47, 44, 50, 48] 3,4 :5: [2, 3, 4, 5, 15, 19, 26, 27, 36, 38, 46, 47, 44, 50, 48] 6,8 :26: [2, 3, 4, 5, 15, 19, 26, 27, 36, 38, 46, 47, 44, 50, 48] 7,8 :27: [2, 3, 4, 5, 15, 19, 26, 27, 36, 38, 46, 47, 44, 50, 48] 10,14 :46:44 [2, 3, 4, 5, 15, 19, 26, 27, 36, 38, 44, 46, 47, 50, 48] 12,14 :47: [2, 3, 4, 5, 15, 19, 26, 27, 36, 38, 44, 46, 47, 50, 48] 13,14 :50:48 [2, 3, 4, 5, 15, 19, 26, 27, 36, 38, 44, 46, 47, 48, 50] [2, 3, 4, 5, 15, 19, 26, 27, 36, 38, 44, 46, 47, 48, 50]