package mainimport"fmt"// QuickSort function sorts an array in-place using left and right pointersfuncQuickSort(arr []int, left, right int) {if left < right { pivotIndex :=partition(arr, left, right)QuickSort(arr, left, pivotIndex-1) // Sort left of pivotQuickSort(arr, pivotIndex+1, right) // Sort right of pivot }}// Partition function rearranges elements around the pivotfuncpartition(arr []int, left, right int) int { pivot := arr[right] // Choosing the last element as the pivot i := left // Initialize i to start of the subarrayfor j := left; j < right; j++ { // Traverse the arrayif arr[j] < pivot { arr[i], arr[j] = arr[j], arr[i] // Swap elements i++// Move the smaller-element pointer } }// Place pivot in its correct sorted position arr[i], arr[right] = arr[right], arr[i]return i // Return the pivot index}funcmain() { arr := []int{10, 7, 8, 9, 1, 5} fmt.Println("Original Array:", arr)QuickSort(arr, 0, len(arr)-1) fmt.Println("Sorted Array:", arr)}
Leave a Reply