What is Sorting? & Bubble Sort Algorithm:
Suppose, you have to arrange books on your bookshelf. There is a number of ways to arranging it. Here we consider arranging the order of Books by their number of pages.
Selection Sort
One way to do it by taking the book with the highest number of pages and put it into Bookshelf. And now from the remaining books choose another book which is having the highest number of pages and put it in bookshelf by side of book which is already there. Repeat this process until there is no book on the bookshelf. In Computer Science, this method called “Selection Sort”.
Insertion Sort

Sorting of Integers demonstrated by C/C++ code in both Sort and Insertion Sort.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*Insertion Sort Function | |
Time Complexity : O(N^2) | |
Space Complexity : O(1) | |
*/ | |
void Insertion_Sort(int data_array[],int SizeOf_data_array) | |
{ | |
int IntegerToBeInsert; | |
//loop for insert all the integers in ascending order | |
//this loop start with second element because One element is already sorted | |
for(int i=1;i<SizeOf_data_array;i++) | |
{ | |
//Integer which is perform as key to be inserted | |
IntegerToBeInsert = data_array[i]; | |
int j=i-1; | |
//Traverse array from end of array to correct postion | |
// ANd shifting of elements to make postion | |
while(j>=0 && data_array[j]>IntegerToBeInsert) | |
{ | |
data_array[j+1]=data_array[j]; | |
j--; | |
} | |
//Insert element @ correct Position | |
data_array[j+1]=IntegerToBeInsert; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*Selection Sort Function | |
Time Complexity : O(N^2) | |
Space Complexity : O(1) | |
*/ | |
void Selection_Sort(int data_array[],int SizeOf_data_array) | |
{ | |
int tmp; | |
//find MAX from existing array | |
//swap it until it moves to last position in array | |
for(int i=0;i<SizeOf_data_array-1;i++) | |
for(int j=i+1;j<SizeOf_data_array;j++) | |
if(data_array[i]>data_array[j]) | |
{ | |
tmp=data_array[i]; | |
data_array[i]=data_array[j]; | |
data_array[j]=tmp; | |
} | |
} |
Comments
Post a Comment