选择排序的思想:(先安排最小值)
选择排序是把第一个数与后面的一次比较,每次比较,如果0索引大于后面的索引,则把0索引与该比较索引的值进行互换。下一次比较时,只需要从1索引开始与所有后面的索引进行比较,如果1索引大于后面的索引,则把1索引与该比较索引的值进行互换。......直到我们比较完所有,这样得到的新数组就是按照从大到小的顺序的数组。
//选择排序法 public class Demo1 { public static void main(String[] args) { int[] arr = {23,12,54,67,32,10,2,41}; System.out.println("排序前:"); print(arr); selectArr(arr); System.out.println("排序后:"); print(arr); } //遍历 public static void print(int[] arr) { for(int x = 0 ;x <arr.length;x++) { System.out.print(arr[x]+ " "); } System.out.println(); } //选择排序 public static void selectArr(int[] arr) { for(int y = 0 ;y <arr.length-1;y++) { for(int x = y+1 ; x < arr.length ; x++) { if(arr[y]>arr[x]) { int temp = arr[y]; arr[y] = arr[x]; arr[x] = temp; } } } } }
冒泡排序的思想:(先安排最大值)
冒泡排序是把两两相邻的索引进行比较,如果前者大于后者,则将两者位置互换。完成一轮的互换位置后,最大值出现在了最大索引出。完成第二轮互换位置后,第二大值出现咋第二大索引处。完成length-1轮比较后,我们就得到了排完序的数组。
代码:
public class Demo2 { public static void main(String[] args) { int[] arr = { 12, 34, 22, 9, 20 }; System.out.println("冒泡排序前:"); print(arr); bubbling(arr); System.out.println("冒泡排序后:"); print(arr); } // 遍历 public static void print(int[] arr) { for (int x = 0; x < arr.length; x++) { System.out.print(arr[x] + " "); } System.out.println(); } // 冒泡 public static void bubbling(int[] arr) { for (int x = 0; x < arr.length - 1; x++) { for (int y = 0; y < arr.length - 1 - x; y++) { if (arr[y] > arr[y + 1]) { int temp = arr[y]; arr[y] = arr[y + 1]; arr[y + 1] = temp; } } } } }
二分查找法的思想:
二分查找法的使用前提是数组一定是
有序的。 需要先定义这个数组的最大索引和最小索引,中间索引,将需要比较的value与中间索引进行比较,如果大于中间索引,则将中间索引赋给最小索引;如果小于中间索引,则将中间索引赋值给最大索引。然后再进行新一轮的比较,这样可以快速的找到我们需要到索引。
例子:
public class Demo3 { public static void main(String[] args) { int[] arr = {11,22,33,44,55,66,77,88}; System.out.println("索引数组:"); SearchTool.print(arr); int num44 = SearchTool.search(arr, 44); System.out.println("index44=" +num44); } } class SearchTool{ public static void print(int[] arr) { for(int x= 0 ;x <arr.length;x++) { System.out.print(arr[x]+ " "); } System.out.println(); } public static int search(int[] arr,int value) { int min = 0 ; int max = arr.length-1; int middle = (min+max)/2; while(arr[middle] != value) { if(arr[middle]>value) { max = middle - 1 ; }else { min = middle + 1 ; } if(max<min) { return -1 ; } } return middle; } }