Program for bubble sort using dynamic array

Program Description

Implements bubble sort on integer array,by dynamically increasing the size of the array as the user gives input.

To stop entering the input values the user is asked to give a sentinel value. After the data is entered the program sorts the given array using bubble sort and displays the result.

Program
/***************************************************
*
*    Program for bubble sort using dynamic array
*    
*    code.cheraus.com
*
****************************************************/

#include <stdio.h>
#include<stdlib.h>
int main()
{
  int input, i,j,c;
  int count=0;       //keeps track of size of array
  int *numbers=NULL;  //pointer to integer array
  int *more;          //pointer to temporary array



  /*dynamically increasing the size of the array as the user gives more input.
    
    Here -1000 is taken as the sentinel value to stop entering more data.
    
  */  

  printf("Enter the numbers(Enter -1000 to stop): ");
  do
  {
    scanf("%d",&input);    
    count++;

    
    //ask for more memory
    more=(int*)realloc(numbers,count*sizeof(int));
    if(more!=NULL)
     {
       
        //if memory allocation successful

       numbers=more;             //make "numbers" point to memory block pointed by "more"
       numbers[count-1]=input;   //store the given number in the array  
     }

    else
     {
       //if there's an error allocating memory
       free(numbers);
       printf("Error reallocating memory");
       exit(1);     //exit out of the program,with return code "1"
     }

     }while(input!=-1000);   //keep asking for more numbers untill,-1000 entered by the user



//print out the given array
 printf("Numbers entered: ");
 for(i=0;i<count-1;i++)
   printf("%d,",numbers[i]);

 printf("\n");



/*       BUBBLE SORT     */

 for(i=0;i<count-1;i++)
   {
     for (j=0;j<count-1-1;j++)
      {
        if (numbers[j] > numbers[j+1])
          {
            c=numbers[j];
            numbers[j]=numbers[j+1];
            numbers[j+1]=c;
          }
      }
   }




 
   //printing the sorted list 
 
  printf("\nSorted list in ascending order:\n");
  for ( i = 0 ; i < count-1 ; i++ )
    printf("%d,", numbers[i]);

    printf("\n");

  free(numbers);  //freeing the memory
  return 0;
}

Output
Test Case 1:

Enter the numbers(Enter -1000 to stop):9
8
7
6
5
4
3
2
1
-1000
Numbers entered: 9,8,7,6,5,4,3,2,1,

Sorted list in ascending order:
1,2,3,4,5,6,7,8,9,



Test Case 2:

Enter the numbers(Enter -1000 to stop):1
3
45
78
90
23
65
78
12
90
45
76
21
-1000
Numbers entered: 1,3,45,78,90,23,65,78,12,90,45,76,21,

Sorted list in ascending order:
1,3,12,21,23,45,45,65,76,78,78,90,90,

Comments
comments powered by Disqus