Choose an index named middleIndex between fist Index and last index of an array which is to be sort.We can get a rearranged array that has the following jfeatures: all elements from first index to middle index is smaller than array[middleindex];all elements from middle index to last index is larger than array[middleindex].The Partition method return the middle index so we can rearrange the two subarray by the same way.
Let’s show it.
//swap two items of the arr privatevoid Swap(Int32[] arr, Int32 firstIndex, Int32 secondIndex) ...{ if (firstIndex < arr.Length && secondIndex < arr.Length) ...{ Int32 temp = arr[firstIndex]; arr[firstIndex] = arr[secondIndex]; arr[secondIndex] = temp; } } //In this method,we use arr[lastIndex] as the middleValue private Int32 Partition(Int32[] arr, Int32 firstIndex, Int32 lastIndex) ...{ if (firstIndex < arr.Length && lastIndex < arr.Length) ...{ Int32 middleValue = arr[lastIndex]; Int32 i = firstIndex -1; for (Int32 j = firstIndex; j < lastIndex; j++) ...{ if (arr[j] <= middleValue) Swap(arr, ++i, j); } Swap(arr, i +1, lastIndex); return i +1; } else ...{ return-1; } } publicvoid Sort(Int32[] arr, Int32 firstIndex, Int32 lastIndex) ...{ if (firstIndex < lastIndex) ...{ Int32 middleIndex = Partition(arr, firstIndex, lastIndex); Sort(arr, firstIndex, middleIndex -1); Sort(arr, middleIndex +1, lastIndex); } }
Ok,it fine.
Let's make a random index between firstIndex and lastIndex,Choose arr[randomIndex] as the middleValue