排序算法 冒泡排序法 选择排序法 思路:选择一个元素作为最小元素(一般是第一个),然后将这个元素与数组其他元素进行比较,如果比它还小则将其最小元素赋值给它,比较完一轮后,将这个最小元素放入到新数组(排序好的数组)并从原数组剔除出去,如此反复操作n轮
**时间复杂度:**O(n²)
代码:
java:
public static int findSmallest (int []arr) { int smallest = arr[0 ]; int smallest_index = 0 ; for (int i = 1 ; i < arr.length; i++) { if (arr[i] < smallest){ smallest = arr[i]; smallest_index = i ; } } return smallest_index; } public static int [] removeElement(int arr[],int element_index){ int []array = new int [arr.length - 1 ]; for (int i = 0 ,j =0 ;i<arr.length;i++){ if (i!=element_index){ array[j++] = arr[i]; } } return array; } public static int [] chooseSort(int arr[]){ int []newArr = new int [arr.length]; int index = 0 ; int len = arr.length ; for (int i = 0 ; i < len; i++) { int smallest_index = findSmallest(arr); newArr[index++] = arr[smallest_index]; arr = removeElement(arr,smallest_index); } return newArr; }
python:
def find_smallest (arr ): smallest = arr[0 ] smallest_index = 0 for i in range (1 , len (arr)): if arr[i] < smallest: smallest = arr[i] smallest_index = i return smallest_index def choose_sort (arr ): sort_list = [] for i in range (len (arr)): smallest_index = find_smallest(arr) sort_list.append(arr.pop(smallest_index)) return sort_list
快速排序法 **思路:**选择数组中的一个元素作为基准元素,然后将其他元素与其比较,如果小的放入左边一个数组,如果大的放入右边的数组,反复操作,直至子数组只有0个或者1个元素为止。
时间复杂度 :O(nlogn)
python:
def quick_sort (arr ): if len (arr) < 2 : return arr pivot = arr[0 ] less = [i for i in arr[1 :] if i <= pivot] right = [i for i in arr[1 :] if i > pivot] return quick_sort(less) + [pivot] + quick_sort(right) print (quick_sort([2 , 7 , 7 , 4 , 1 , 9 , 5 , 3 , 6 , 8 ]))
java:
public static int [] quickSort(int []arr){ if (arr.length <= 1 ){ return arr; } int privot = arr[0 ]; ArrayList<Integer> less = new ArrayList <>(); ArrayList<Integer> greater = new ArrayList <>(); for (int i = 1 ; i < arr.length ; i++) { if (arr[i] >= privot) { greater.add(arr[i]); }else { less.add(arr[i]); } } int [] lessArr = quickSort(less.stream().mapToInt(Integer::valueOf).toArray()); int [] greaterArr = quickSort(greater.stream().mapToInt(Integer::valueOf).toArray()); int []array = new int [arr.length]; System.arraycopy(lessArr,0 ,array,0 ,lessArr.length); System.arraycopy(greaterArr,0 ,array,lessArr.length+1 ,greaterArr.length); array[lessArr.length] = privot ; return array ; }