In this tutorial, we will learn how to sort two arrays in the C programming language. Sorting is an important operation that is often required while working with arrays or lists. We will first provide a step-by-step approach to sort two arrays individually and then show how to sort the arrays in a combined manner.
Step 1: Sort arrays individually
The most basic approach to sorting two arrays is to sort each of them independently using a sorting algorithm like the Bubble Sort, Selection Sort, or Quick Sort. Here we are going to use the Bubble Sort algorithm because of its simplicity and ease of implementation.
Here is our C code for sorting arrays individually using Bubble Sort:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
// Function that implements Bubble Sort void bubbleSort(int arr[], int size) { int i, j, temp; for (i = 0; i < size - 1; i++) { for (j = 0; j < size - i - 1; j++) { if (arr[j] > arr[j + 1]) { temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } int main() { int arr1[] = {64, 34, 25, 12, 22, 11, 90}; int arr2[] = {45, 23, 78, 1, 6, 43}; int n1 = sizeof(arr1) / sizeof(arr1[0]); int n2 = sizeof(arr2) / sizeof(arr2[0]); bubbleSort(arr1, n1); bubbleSort(arr2, n2); return 0; } |
Output:
Sorted array1: 11 12 22 25 34 64 90 Sorted array2: 1 6 23 43 45 78
Step 2: Sort two arrays together
Next, let’s learn to sort two arrays in a combined manner. The approach we’re going to use here is similar to the Merge operation in the Merge Sort algorithm.
Here is the C code for sorting two arrays together:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
#include <stdio.h> void sortTogether(int arr1[], int size1, int arr2[], int size2) { int i = 0, j = 0, k = 0; int sortedArray[size1 + size2]; // Merge arrays while (i < size1 && j < size2) { if (arr1[i] < arr2[j]) { sortedArray[k++] = arr1[i++]; } else { sortedArray[k++] = arr2[j++]; } } // Copy remaining elements of arr1[] if any while (i < size1) { sortedArray[k++] = arr1[i++]; } // Copy remaining elements of arr2[] if any while (j < size2) { sortedArray[k++] = arr2[j++]; } // Print sorted array for (int x = 0; x < size1 + size2; x++) { printf("%d ", sortedArray[x]); } } int main() { int arr1[] = {11, 12, 22, 25, 34, 64, 90}; int arr2[] = {1, 6, 23, 43, 45, 78}; int n1 = sizeof(arr1) / sizeof(arr1[0]); int n2 = sizeof(arr2) / sizeof(arr2[0]); sortTogether(arr1, n1, arr2, n2); return 0; } |
Output:
1 6 11 12 22 23 25 34 43 45 64 78 90
Conclusion
In this tutorial, we have learned how to sort two arrays in the C programming language using an individual sorting approach as well as a combined sorting approach. With the knowledge of these algorithms, you should be able to sort any given arrays according to your specific needs.