Showing posts with label sort. Show all posts
Showing posts with label sort. Show all posts

Saturday, September 22, 2012

C Program To Sort An Array Using Bubble Sort


#include<stdio.h>
int main() {
 int a[50], n, i, j, temp = 0;

 printf("Enter how many numbers you want:\n");
 scanf("%d", &n);
 printf("Enter the %d elements:\n", n);
 for (i = 0; i < n; i++) {
  scanf("%d", &a[i]);
 }
 printf("\n\t\tThe given array is:\n");
 for (i = 0; i < n; i++) {
  printf("\n\t\t%d", a[i]);
 }
 for (i = 0; i < n; i++) {
  for (j = i + 1; j < n; j++) {
   if (a[i] > a[j]) {
    temp = a[i];
    a[i] = a[j];
    a[j] = temp;
   }
  }
 }

 printf("\n\n\n\t\tThe sorted array using Buble sort is:\n");
 for (i = 0; i < n; i++) {
  printf("\n\t\t%d", a[i]);
 }
 return 0;
}

Friday, September 21, 2012

selection sort in c


#include<stdio.h>

main()
{
   int array[100], n, c, d, position, swap;

   printf("Enter number of elements\n");
   scanf("%d", &n);

   printf("Enter %d integers\n", n);

   for ( c = 0 ; c < n ; c++ )
      scanf("%d", &array[c]);

   for ( c = 0 ; c < ( n - 1 ) ; c++ )
   {
      position = c;

      for ( d = c + 1 ; d < n ; d++ )
      {
         if ( array[position] > array[d] )
            position = d;
      }
      if ( position != c )
      {
         swap = array[c];
         array[c] = array[position];
         array[position] = swap;
      }
   }

   printf("Sorted list in ascending order:\n");

   for ( c = 0 ; c < n ; c++ )
      printf("%d\n", array[c]);

   return 0;
}