How to write a C Program to Multi Array Sorting/Searching in C Programming Language ?
This C Program to Multi Array Sorting/Searching.Solution:
- #include <stdio.h>
- int arrayTotal[500], multiArray[10][50], arraySize, number, arrayCount, n;
- void sortArrays(int arr[], int length);
- void printArray(int arr[], int length);
- void binarySearch(int arr[], int length, int item);
- int main()
- {
- printf("Enter the amount of arrays (max 10): ");
- scanf("%d", &arrayCount);
- printf("Enter size of arrays (max 50): ");
- scanf("%d", &arraySize);
- printf("\nEnter the elements for the first array...\n");
- for (int i = 0; i < arrayCount; i++) {
- printf("Now for the next array...\n");
- for (int j = 1; j <= arraySize; j++) {
- printf("%d: ", j);
- scanf("%d", &multiArray[i][j - 1]);
- }
- }
- //print the double array
- printf("Here is your array of arrays...\n");
- for (int i = 0; i < arrayCount; i++) {
- printArray(multiArray[i], arraySize);
- }
- //combine the double array into one long array and sort it
- //then separate that array back into a multi array
- printf("Let's sort that array of arrays...\n");
- n = 0;
- for (int i = 0; i < arrayCount; i++) {
- for (int j = 0; j < arraySize; j++) {
- arrayTotal[n] = multiArray[i][j];
- n++;
- }
- }
- sortArrays(arrayTotal, arraySize*arrayCount);
- n = 0;
- for (int i = 0; i < arrayCount; i++) {
- for (int j = 0; j < arraySize; j++) {
- multiArray[i][j] = arrayTotal[n];
- n++;
- }
- }
- //print the arrays again
- printf("Here is your sorted array of arrays...\n");
- for (int i = 0; i < arrayCount; i++) {
- printArray(multiArray[i], arraySize);
- }
- //find an item in the array
- printf("Let's find an item! Which item do you want to find? ");
- scanf("%d", &number);
- binarySearch(arrayTotal, arraySize * 2, number);
- return 0;
- }
- //this function uses a bubble sort to sort the array in ascending order
- void sortArrays(int arr[], int length) {
- for (int i = 0; i < length - 1; i++) {
- for (int j = 0; j < length - i - 1; j++) {
- if (arr[j] > arr[j + 1]) {
- int temp = arr[j];
- arr[j] = arr[j + 1];
- arr[j + 1] = temp;
- }
- }
- }
- }
- //this is just a simple function to print the arrays
- void printArray(int arr[], int length) {
- for (int i = 0; i < length; i++) {
- printf("%d ", arr[i]);
- }
- printf("\n");
- }
- //This is the binary search function
- void binarySearch(int arr[], int length, int item) {
- int first = 0;
- int last = length - 1;
- int mid = (int)((first + last) / 2);
- while (first <= last) {
- if (arr[mid] < item) {
- first = mid + 1;
- }
- else if (arr[mid] == item) {
- printf("That is element number %d\n", mid+1);
- break;
- }
- else {
- last = mid - 1;
- }
- mid = (int)((first + last) / 2);
- }
- if (first > last) {
- printf("That item isn't in the list...\n");
- }
- }