Pages

Tuesday, August 30, 2011

Array Sorting Program with C and C++

This article will show how to sort array elements with C and C++ program. The most popular Bubble Sorting algorithm is used in this program. The following program will first store inputs into array with the scanf() function and then Bubble sort algorithm is applied to sort the array elements. The complete programming code is given below. 



Array Sorting Program

#include<stdio.h>
#include<conio.h>

  void main()
  {
            int a[20],N;
            clrscr();

            printf("How many array elements:");
            scanf("%d",&N);
            printf("Enter elements:\n");

            // Storing elements into an array


            for(int i=0;i<N;i++)  
            {
                 scanf("%d",&a[i]);
            }

             // Showing  unsorted array elements

            printf("Array is :"); 
            for(i=0;i<N;i++)
            {
                  printf("%d  ",a[i]);
            }

             //sorting array elements with Bubble sort algorithm


            for(i=0;i<N;i++)
            {
              int ptr=0;
              while(ptr<N-1-i)
              {
                if(a[ptr]>a[ptr+1])
                 {
                         int temp=a[ptr];
                         a[ptr]=a[ptr+1];
                         a[ptr+1]=temp;
                 }
                        ptr=ptr+1;
              }
            }

           // Showing sorted array elements

           printf("\nSorted array :"); 
           for(i=0;i<N;i++)
            {
                   printf("%d  ",a[i]);
            }
    getch ();
  } 

Output
  

4 comments:

Anafam said...

do u have a coding for sorting an array using the selection sorting method?

Unknown said...

thanks for sharing! I finally understood :)
BTW, I also have a blog and a web directory, would you like to exchange links? let me know on emily.kovacs14@gmail.com

Anonymous said...

Hi there, I do think your web site might be having browser compatibility
issues. Whenever I take a look at your site in Safari, it looks fine however,
when opening in Internet Explorer, it has some overlapping
issues. I simply wanted to give you a quick heads up!
Aside from that, great website!

Feel free to visit my blog post ... best diet plan

Anonymous said...

Hello there, just became aware of your blog through
Google, and found that it is really informative. I'm gonna watch out for brussels. I will be grateful if you continue this in future. Numerous people will be benefited from your writing. Cheers!

My website - http://www.vigrxenhancer.com/