gpt-3.5-turbo-0613· openai
Suzhen/CodeChat
please give me a quick sort algorithm written in C++
- User
please give me a quick sort algorithm written in C++
- Assistant
Here is an implementation of the Quick Sort algorithm in C++:
#include <iostream> using namespace std; // Function to swap two elements void swap(int* a, int* b) { int t = *a; *a = *b; *b = t; } // Function to partition the array and return the partitioning index int partition(int arr[], int low, int high) { int pivot = arr[high]; int i = (low - 1); for (int j = low; j <= high - 1; j++) { if (arr[j] < pivot) { i++; swap(&arr[i], &arr[j]); } } swap(&arr[i + 1], &arr[high]); return (i + 1); } // Function to perform Quick Sort void quickSort(int arr[], int low, int high) { if (low < high) { // Find the partitioning index int pi = partition(arr, low, high); // Recursively sort the left and right halves quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); } } // Function to print the array void printArray(int arr[], int size) { for (int i = 0; i < size; i++) cout << arr[i] << " "; cout << endl; } // Driver code int main() { int arr[] = { 64, 25, 12, 22, 11 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "Original array: "; printArray(arr, n); quickSort(arr, 0, n - 1); cout << "Sorted array: "; printArray(arr, n); return 0; }This code demonstrates the Quick Sort algorithm by sorting an array of integers. You can modify the input array as per your requirements.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.