Computer programming

Sorting is a common operation used in programming. Although languages such as Visual Basic 2008 offer built-in methods for sorting, other languages such as C do not support such a method. In order to be a programmer you should be able to implement such programming logic using programming languages. Read about two different types of sorting methods early in the week and write a modular program that performs the following functions: * Allows the user to enter 10 integers for sorting * Allows the user to select one of the two types of sorting techniques * Allows the user to select either the ascending or descending order * Displays the sorted list of numbers according to the options selected by the user

Answers

Below is an example program in C to perform the four tasks outlined above. #include /* function to swap two elements a and b */ void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } /* Bubble Sort algorithm for sorting list of numbers */ void bubble_sort(int array[], int n, int order) { int i, j; order = order == 0 // order == 0 indicates ascending order ? 1 : -1; // order != 0 indicates descending order // ? (ternary operator) sets order = 1 or -1 for (i = 0; i < n - 1; i++) for (j = 0; j < n - i - 1; j++) { if (order * array[j] > order * array[j + 1]) swap(&array[j], &array[j + 1]); } } /* main function to test bubble_sort function */

Answered by Joseph Boyd

We have mentors from

Contact support