Write a C program called sortc that first prompts the user f

Write a C program called sort.c that first prompts the user for a positive number n representing the number of numbers to be sorted. Next, it prompts the user to enter the numbers in an arbitrary order and store them in an array of size n. The program then takes the following approach to sort the numbers in the array: a. it stores the value of n in a temporary variable temp,
b. it searches for the largest number in the array, starting with position 0 and ending with position temp-1 (use the previous algorithm for finding the largest element of an array), c. it then switches the field that stores the largest value with the field indexed by temp-1, d. the program decrements temp by 1 (temp--), e. the program repeats steps b-d until temp is decremented to 1 in step d.
The program then prints the numbers of the array to the screen on a single line with a whitespace between the numbers and then terminates. Please note that in step c., the program does not need to switch values if the largest value is already located in temp-1.

Solution

// C code sort.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
   int n,i;

   printf(\"Enter size of array: \");
   scanf(\"%d\",&n);

   int array[n];

   for ( i = 0; i < n; ++i)
   {
      printf(\"Enter integer %d: \", i+1);
      scanf(\"%d\",&array[i]);
   }

   int temp = n;

   // earches for the largest number in the array,
   // starting with position 0 and ending with position temp-1
   while(temp-- != 1)
   {
      int largest_index = 0;
      for ( i = 0; i <= temp; ++i)
      {
          if(array[i] > array[largest_index])
            largest_index = i;
      }

      // switches the field that
      // stores the largest value with the field indexed by temp-1
      int t = array[largest_index];
      array[largest_index] = array[temp];
      array[temp] = t;
   }

   printf(\"\ \");
   printf(\"Sorted array: \ \");
   // prints the numbers of the array to the screen
   // on a single line with a whitespace between the numbers
   for ( i = 0; i < n; ++i)
   {
      printf(\"%d \",array[i] );
   }

   printf(\"\ \");
   return 0;
}


/*
output:

Enter size of array: 10
Enter integer 1: 3
Enter integer 2: 5
Enter integer 3: 6
Enter integer 4: 12
Enter integer 5: 43
Enter integer 6: 21
Enter integer 7: 67
Enter integer 8: 32
Enter integer 9: 11
Enter integer 10: 10

Sorted array:
3 5 6 10 11 12 21 32 43 67

*/

Write a C program called sort.c that first prompts the user for a positive number n representing the number of numbers to be sorted. Next, it prompts the user t
Write a C program called sort.c that first prompts the user for a positive number n representing the number of numbers to be sorted. Next, it prompts the user t

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site