Posts

Showing posts with the label Bubble sort

Bubble sort in C++

  #include<iostream>  //header file using namespace std ;     //header file int main ()    //main function { int i , j , temp = 0 , n , a [ 20 ];      //declaration and initialization of variables cout << "Enter the array size : \n" ;    //prints the msg on output screen cin >> n ;  //stores value in variable n cout << "\nEnter the array element:\n" ;    //prints the msg on output screen for ( i = 0 ; i < n ; i ++)    //for loop runs from i=0 to i=n-1 cin >> a [ i ];       //stores value in a[i] for ( i = 0 ; i < n ; i ++)    //for loop runs from i=0 to i=n-1 { for ( j = 0 ; j < n - i ; j ++)      //for loop runs from j=0 to j=n-i { if ( a [ j ]> a [ j + 1 ])    //if block { temp = a [ j ];      //storing value of a[j] in temp a [ j ]= a [ j + i ];...

Bubble sort in C

#include<stdio.h> int main() { int i,j,temp=0,n,a[20]; printf("Enter the array size=\n"); scanf("%d",&n); printf("\nEnter the array element:\n"); for(i=0;i<n;i++) scanf("%d",&a[i]); for(i=0;i<n;i++) { for(j=0;j<n-i;j++) { if(a[j]>a[j+1]) { temp=a[j]; a[j]=a[j+i]; a[j+1]=temp; } } } printf("sorted array:\n"); for(i=0;i<n;i++) printf("%d\t",a[i]); return 0; } output: Enter the array size= 5 Enter the array element: 4 5 9 8 7 sorted array: 4       5       7     8      9