Pages

2013-04-15

Bubble Sort


Bubble Sort is a sorting algorithm  that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm gets its name from the way smaller elements "bubble" to the top of the list. ----------- from WIKI


Sort the following  numbers ascending using Bubble Sort and implement by C.

100, 50, 67, 25, 34, 20, 70





#include<stdio.h>
#include<stdlib.h>
void sort(int arr[]);
int main(void) {
 //setvbuf(stdout, NULL, _IONBF, 0);
 //setvbuf(stderr, NULL, _IONBF, 0);
 int A[7]={100,50,67,25,34,20,70};
 int i;
 printf("before sorting, A[] = ");
 for(i=0;i<7;i++){
  printf("%d ",A[i]);
 }
 printf("; after sorting, A[] = ");
 sort(A);
 for(i=0;i<7;i++){
   printf("%d ",A[i]);
  }
 return 0;
}

void sort(int arr[]){
 int i,j,temp;
 for(i=1;i<7;i++){
  for(j=0;j<7-i;j++){
   if (arr[j]>arr[j+1]){
    temp=arr[j];
    arr[j]=arr[j+1];
    arr[j+1]=temp;
   }
  }
 }
}
Output:

before sorting, A[] = 100 50 67 25 34 20 70 ; after sorting, A[] = 20 25 34 50 67 70 100
References : http://en.wikipedia.org/wiki/Bubble_sort

No comments:

Post a Comment