There are many different types of sorting, including, merge sort, insertion sort, bubble sort, quick sort, e.t.c.,. Today I'm gonna show you how to implement bubble sort in C++. This program is very important in exam point-of-view and computer science theory point-of-view. Here is an awesome representation of bubble sort:
The aim is to display a set of numbers given by the user in ascending or descending order.
Code:
For newer IDEs, visit this page.
Working:
First we input the numbers into an array. Now we compare each element with the next element. If the first element is greater than the second, we just swap the values. So at last, the elements will be in order. Simple, huh?
Happy Coding!
Bubble Sort Source : Wikipedia Commons |
The aim is to display a set of numbers given by the user in ascending or descending order.
Code:
#include<iostream.h> #include<conio.h> void main() { int i,j,a[100],num,t; cout<<"Enter the number of numbers : \n"; cin>>num; cout<<"Enter the numbers to sort : \n"; for(i=0;i<num;i++) { cin>>a[i]; } for(i=0;i<num;i++) { for(j=0;j<num-1;j++) { if(a[j]>a[j+1]) { t=a[j]; a[j]=a[j+1]; a[j+1]=t; } } } for(i=0;i<num;i++) { cout<<a[i]<<"\t"; } cout<<"\n"; }
For newer IDEs, visit this page.
Working:
First we input the numbers into an array. Now we compare each element with the next element. If the first element is greater than the second, we just swap the values. So at last, the elements will be in order. Simple, huh?
Happy Coding!
No comments:
Post a Comment