Welcome to the fascinating world of C programming! Today, we'll dive deep into one of the most essential topics - Array Sorting. 📝
Arrays are a collection of elements of the same data type, stored in contiguous memory locations. They are defined using square brackets [].
int numbers[5] = {1, 2, 3, 4, 5};In this example, numbers is an array of 5 integers, and we've initialized it with values 1 through 5.
Sorting arrays is crucial for many real-world applications, such as sorting student grades, arranging data in a database, or even in algorithms like Quick Sort and Merge Sort. Sorting helps us organize data in a logical and easily searchable manner.
Let's explore the most fundamental sorting algorithm - Bubble Sort. This algorithm repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order.
void bubbleSort(int arr[], int n) {
for(int i = 0; i < n-1; i++) {
for(int j = 0; j < n-i-1; j++) {
if(arr[j] > arr[j+1]) {
swap(&arr[j], &arr[j+1]);
}
}
}
}In this code, we've defined a function bubbleSort that takes an array arr and its length n. Inside the function, we use two nested for loops to compare and swap elements if necessary.
Quick Sort is a more efficient algorithm that works by selecting a 'pivot' element and partitioning the array around it.
void quickSort(int arr[], int low, int high) {
if(low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi-1);
quickSort(arr, pi+1, high);
}
}
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);
}In this code, we've defined quickSort and partition functions. The quickSort function recursively partitions the array around the pivot, while the partition function selects a pivot, partitions the array, and returns the pivot's new position.
Which sorting algorithm does the provided Quick Sort code implement?
Remember, practice makes perfect! Try implementing these sorting algorithms in your own C programs to gain a deeper understanding. Happy coding! 🚀