gpt-4-1106-preview· OpenAI
WildChat-4.8M (AI2)
Write me a Quick sort algorithm in C with function that will generate array of random n…
- User
Write me a Quick sort algorithm in C with function that will generate array of random n numbers
- Assistant
Write me a Quick sort algorithm in C with function that will generate array of random n numbers
Here is an implementation of the Quick Sort algorithm in C, along with a function to generate an array of n random numbers:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// function to generate an array of n random numbers
void generateRandomArray(int array[], int n) {
// use current time as seed for random generator
srand(time(NULL));
for (int i = 0; i < n; i++) {
// generate random number within some range, for example 0 to 999
array[i] = rand() % 1000;
}
}
// quicksort functions
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
int partition(int array[], int low, int high) {
int pivot = array[high]; // taking the last element as pivot
int i = (low - 1); // index of smaller element
for (int j = low; j < high; j++) {
// if current element is smaller than or equal to pivot
if (array[j] <= pivot) {
i++; // increment index of smaller element
swap(&array[i], &array[j]);
}
}
swap(&array[i + 1], &array[high]);
return (i + 1);
}
void quickSort(int array[], int low, int high) {
if (low < high) {
// pi is partitioning index, array[p] is now at right place
int pi = partition(array, low, high);
// separately sort elements before partition and after partition
quickSort(array, low, pi - 1);
quickSort(array, pi + 1, high);
}
}
// function to print array
void printArray(int array[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", array[i]);
}
printf("\n");
}
int main() {
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
int* array = malloc(n * sizeof(int));
if (!array) {
printf("Memory allocation failed!\n");
return -1;
}
generateRandomArray(array, n);
printf("Random array: \n");
printArray(array, n);
quickSort(array, 0, n - 1);
printf("Sorted array: \n");
printArray(array, n);
free(array);
return 0;
}
This code includes the main function where you:
Before executing the code, make sure that the rand function provides a sufficiently random distribution for your needs. For actual cryptographic or security-related work, you would need to use a more secure random number generator. The above code intends to serve educational purposes rather than production use.
Not yet included in a published release.