QuickSort
Java Code:
1 import java.util.*; 2 public class quickSort{ 3 public static void main(String [] args){ 4 int [] arr = new int[]{4,2,7,5,0,9,1}; 5 int low = 0; 6 int high = arr.length-1; 7 quickSort(arr, low, high); 8 System.out.println(Arrays.toString(arr)); 9 } 10 11 private static void quickSort(int [] arr, int low, int high){ 12 if(arr == null || arr.length == 0){ 13 return; 14 } 15 16 if(low >= high){ 17 return; 18 } 19 20 int pivot = arr[low + (high - low)/2]; 21 22 //make left < pivot, right > pivot 23 int i = low; 24 int j = high; 25 while(i <= j){ 26 while(arr[i] < pivot){ 27 i++; 28 } 29 while(arr[j] > pivot){ 30 j--; 31 } 32 33 if(i <= j){ 34 int temp = arr[i]; 35 arr[i] = arr[j]; 36 arr[j] = temp; 37 i++; 38 j--; 39 } 40 } 41 42 //recursively sort two sub arrays 43 quickSort(arr, low, j); 44 quickSort(arr, i, high); 45 } 46 }
时间: 2024-10-12 13:19:24