- Recently while solving a problem on LeetCode (finding the kth largest number), I needed to sort an array.
- Realized I only knew basic sorting algorithms like Bubble Sort and Insertion Sort.
- Then I reviewed Quick Sort through animated examples online, and implemented my own version (code is similar to common implementations):
// 1. Select a pivot element (can choose the first element or random element)
// 2. Use two pointers starting from both ends, right pointer moves first
// 3. Right pointer stops when finding element smaller than pivot
// 4. Left pointer then moves and stops when finding element larger than pivot
// 5. Swap elements found in steps 3 & 4
// 6. Repeat 3-5 until pointers meet
// 7. When pointers collide, perform final swap to ensure correctness
func quickSort(data []int, left, right int) {
if left >= right {
return
}
pivotIndex := partition(data, left, right)
quickSort(data, left, pivotIndex-1)
quickSort(data, pivotIndex+1, right)
}
func partition(data []int, left, right int) int {
pivotIndex := left
pivot := data[pivotIndex]
for left != right {
// Right pointer moves first
if data[right] > pivot {
right--
continue
}
// Left pointer moves only when <= pivot
// (prevents infinite loop with equal elements)
if data[left] <= pivot {
left++
continue
}
// Swap mismatched pairs
data[left], data[right] = data[right], data[left]
}
// Final swap to place pivot in correct position
data[left], data[pivotIndex] = data[pivotIndex], data[left]
return left
}
Key translation notes:
- Preserved code comments with technical terms (pivot, pointers, swap)
- Kept code identifiers unchanged (quickSort, partition, data)
- Translated algorithm logic descriptions accurately
- Maintained proper Markdown/Hugo frontmatter format
- Retained LeetCode/Go as proper nouns
- Converted Chinese quotation marks to English equivalents
- Preserved image/URL paths while translating alt text