code for quick sort
- User
code for quick sort
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
code for quick sort
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Here's Quick Sort implemented in multiple programming languages. Quick Sort is a highly efficient divide-and-conquer sorting algorithm that works by selecting a 'pivot' element and partitioning the array around it.
Quick Sort follows these steps:
def quicksort(arr):
"""
Sorts an array using the Quick Sort algorithm.
This is a simple, readable implementation.
"""
# Base case: arrays with 0 or 1 element are already sorted
if len(arr) <= 1:
return arr
# Choose the middle element as pivot
pivot = arr[len(arr) // 2]
# Partition: elements less than, equal to, and greater than pivot
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
# Recursively sort the partitions and combine
return quicksort(left) + middle + quicksort(right)
def quicksort_inplace(arr, low=0, high=None):
"""
In-place Quick Sort implementation (more memory efficient).
Modifies the original array instead of creating new ones.
"""
if high is None:
high = len(arr) - 1
if low < high:
# Find partition index
pi = partition(arr, low, high)
# Recursively sort elements before and after partition
quicksort_inplace(arr, low, pi - 1)
quicksort_inplace(arr, pi + 1, high)
return arr
def partition(arr, low, high):
"""
Partitions the array using the last element as pivot.
Places pivot in its correct position and returns its index.
"""
# Choose the rightmost element as pivot
pivot = arr[high]
# Index of smaller element - indicates the right position
# of pivot found so far
i = low - 1
for j in range(low, high):
# If current element is smaller than or equal to pivot
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
# Place pivot in its correct position
arr[i + 1], arr[high] = arr[high], arr[i + 1]
return i + 1
# Example usage
if __name__ == "__main__":
# Test the simple version
data = [64, 34, 25, 12, 22, 11, 90]
print("Original array:", data)
sorted_data = quicksort(data)
print("Sorted array: ", sorted_data)
# Test the in-place version
data2 = [64, 34, 25, 12, 22, 11, 90]
print("\nIn-place sorting:")
print("Original array:", data2)
quicksort_inplace(data2)
print("Sorted array: ", data2)
import java.util.Arrays;
public class QuickSort {
public static void quickSort(int[] arr, int low, int high) {
if (low < high) {
// Find partition index
int pi = partition(arr, low, high);
// Recursively sort elements before and after partition
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
private static int partition(int[] arr, int low, int high) {
// Choose the rightmost element as pivot
int pivot = arr[high];
// Index of smaller element - indicates the right position
// of pivot found so far
int i = low - 1;
for (int j = low; j < high; j++) {
// If current element is smaller than or equal to pivot
if (arr[j] <= pivot) {
i++;
// Swap arr[i] and arr[j]
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
// Swap arr[i+1] and arr[high] (or pivot)
int temp = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp;
return i + 1;
}
// Alternative partition method using middle element as pivot
private static int partitionMiddle(int[] arr, int low, int high) {
int mid = low + (high - low) / 2;
int pivot = arr[mid];
// Move pivot to end
int temp = arr[mid];
arr[mid] = arr[high];
arr[high] = temp;
return partition(arr, low, high);
}
// Overloaded method for easier usage
public static void quickSort(int[] arr) {
quickSort(arr, 0, arr.length - 1);
}
public static void main(String[] args) {
int[] data = {64, 34, 25, 12, 22, 11, 90};
System.out.println("Original array: " + Arrays.toString(data));
quickSort(data);
System.out.println("Sorted array: " + Arrays.toString(data));
// Test with duplicate values
int[] data2 = {5, 2, 8, 2, 9, 1, 5, 5};
System.out.println("\nArray with duplicates: " + Arrays.toString(data2));
quickSort(data2);
System.out.println("Sorted array: " + Arrays.toString(data2));
}
}
#include <iostream>
#include <vector>
#include <algorithm>
class QuickSort {
public:
// Main quicksort function
static void quickSort(std::vector<int>& arr, int low, int high) {
if (low < high) {
// Find partition index
int pi = partition(arr, low, high);
// Recursively sort elements before and after partition
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
// Overloaded function for easier usage
static void quickSort(std::vector<int>& arr) {
quickSort(arr, 0, arr.size() - 1);
}
private:
// Lomuto partition scheme
static int partition(std::vector<int>& arr, int low, int high) {
// Choose the rightmost element as pivot
int pivot = arr[high];
// Index of smaller element
int i = low - 1;
for (int j = low; j < high; j++) {
// If current element is smaller than or equal to pivot
if (arr[j] <= pivot) {
i++;
std::swap(arr[i], arr[j]);
}
}
// Place pivot in its correct position
std::swap(arr[i + 1], arr[high]);
return i + 1;
}
// Alternative: Hoare partition scheme (often more efficient)
static int partitionHoare(std::vector<int>& arr, int low, int high) {
int pivot = arr[low];
int i = low - 1;
int j = high + 1;
while (true) {
// Find leftmost element >= pivot
do {
i++;
} while (arr[i] < pivot);
// Find rightmost element <= pivot
do {
j--;
} while (arr[j] > pivot);
// If pointers crossed, partitioning is complete
if (i >= j) {
return j;
}
std::swap(arr[i], arr[j]);
}
}
};
// Function to print array
void printArray(const std::vector<int>& arr) {
for (int x : arr) {
std::cout << x << " ";
}
std::cout << std::endl;
}
int main() {
std::vector<int> data = {64, 34, 25, 12, 22, 11, 90};
std::cout << "Original array: ";
printArray(data);
QuickSort::quickSort(data);
std::cout << "Sorted array: ";
printArray(data);
// Test with random pivot selection
std::vector<int> data2 = {3, 7, 8, 5, 2, 1, 9, 5, 4};
std::cout << "\nAnother test: ";
printArray(data2);
QuickSort::quickSort(data2);
std::cout << "Sorted array: ";
printArray(data2);
return 0;
}
// Simple, functional approach
function quickSort(arr) {
// Base case
if (arr.length <= 1) {
return arr;
}
// Choose middle element as pivot
const pivotIndex = Math.floor(arr.length / 2);
const pivot = arr[pivotIndex];
// Partition array
const left = [];
const right = [];
const equal = [];
for (let element of arr) {
if (element < pivot) {
left.push(element);
} else if (element > pivot) {
right.push(element);
} else {
equal.push(element);
}
}
// Recursively sort and combine
return [...quickSort(left), ...equal, ...quickSort(right)];
}
// In-place implementation
function quickSortInPlace(arr, low = 0, high = arr.length - 1) {
if (low < high) {
// Find partition index
const pi = partition(arr, low, high);
// Recursively sort elements before and after partition
quickSortInPlace(arr, low, pi - 1);
quickSortInPlace(arr, pi + 1, high);
}
return arr;
}
function partition(arr, low, high) {
// Choose the rightmost element as pivot
const pivot = arr[high];
// Index of smaller element
let i = low - 1;
for (let j = low; j < high; j++) {
// If current element is smaller than or equal to pivot
if (arr[j] <= pivot) {
i++;
// Swap elements
[arr[i], arr[j]] = [arr[j], arr[i]];
}
}
// Place pivot in its correct position
[arr[i + 1], arr[high]] = [arr[high], arr[i + 1]];
return i + 1;
}
// Randomized Quick Sort (helps avoid worst-case performance)
function randomizedQuickSort(arr, low = 0, high = arr.length - 1) {
if (low < high) {
// Randomly choose a pivot and swap it with the last element
const randomIndex = low + Math.floor(Math.random() * (high - low + 1));
[arr[randomIndex], arr[high]] = [arr[high], arr[randomIndex]];
const pi = partition(arr, low, high);
randomizedQuickSort(arr, low, pi - 1);
randomizedQuickSort(arr, pi + 1, high);
}
return arr;
}
// Example usage
console.log("=== Simple Quick Sort ===");
const data1 = [64, 34, 25, 12, 22, 11, 90];
console.log("Original:", data1);
console.log("Sorted: ", quickSort(data1));
console.log("\n=== In-Place Quick Sort ===");
const data2 = [64, 34, 25, 12, 22, 11, 90];
console.log("Original:", data2);
quickSortInPlace(data2);
console.log("Sorted: ", data2);
console.log("\n=== Randomized Quick Sort ===");
const data3 = [64, 34, 25, 12, 22, 11, 90];
console.log("Original:", data3);
randomizedQuickSort(data3);
console.log("Sorted: ", data3);
Let's trace through Quick Sort with the array: [3, 7, 8, 5, 2, 1, 9, 5, 4]
Initial call: quickSort([3, 7, 8, 5, 2, 1, 9, 5, 4], 0, 8)
Step 1: First Partition (pivot = 4)
[3, 2, 1, 4][7, 8, 5, 9, 5][3, 2, 1, 4, 7, 8, 5, 9, 5]Step 2: Recursively sort left side [3, 2, 1]
[1, 2, 3]Step 3: Recursively sort right side [7, 8, 5, 9, 5]
[5, 5, 7, 8, 9]Final sorted array: [1, 2, 3, 4, 5, 5, 7, 8, 9]
Quick Sort is generally very efficient, but its performance depends on pivot selection:
Time Complexity:
Space Complexity:
Advantages:
Disadvantages:
Optimization Strategies: