Monday, June 30, 2014

Bubble Sort

Bubble sort is a sorting algorithm that works by repeatedly stepping through lists that need to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. This passing procedure is repeated until no swaps are required, indicating that the list is sorted. Bubble sort gets its name because smaller elements bubble toward the top of the list. 

Source Code:

#include<stdio.h>
#include<conio.h>
int data[10]={22,65,1,99,32,17,74,49,33,2};
int n=10;
void bubble(void);
void main()
{
    int i;
    //clrscr(); This will not work at Dev c++
    bubble();
    printf("The values from array after sorted: \n");
    for (i=0;i<10;i++)
        printf(" %d",data[i]);
   
    getch();
}
void bubble(void)
{
    int k,ptr,temp;
    for(k=0;k<=n-1-1;k++)
    {
        ptr=0;
        while(ptr<=(n-k-1-1))
        {
            if(data[ptr]>data[ptr+1])
            {
                temp=data[ptr];
                data[ptr]=data[ptr+1];
                data[ptr+1]=temp;
            }
            ptr+=1;
        }
    }
}

3 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. #include
    using namespace std;
    int main(string args[])
    {
    int a[10]={89,2,87,25,17,5,9,6,10,11},i=0,j,len=10,temp;
    for(i=0;i<5;i++){
    for(j=0;ja[j+1])
    {
    temp=a[j];
    a[j]=a[j+1];
    a[j+1]=temp;
    }
    }len--;
    }
    for(i=0;i<10;i++)
    {
    cout<<a[i]<<endl;
    }

    }

    ReplyDelete