C++ Programming Articles

Submit Article
Home » Articles » C++ Programming » Data File StructureRSS Feeds

Algorithms of selection sort, bubble sort, merge sort, quick sort and insertion sort

Posted By: Luisa Fischer     Category: C++ Programming     Views: 27006

This article provides an algorithm of selection sort, bubble sort, merge sort, quick sort and insertion sort.

Algorithm for Selection Sort

1.[Loop on pass index]
Repeat through step 4 for pass=1 to n-1.

2.Initialize minindex
minindex <--- pass.

3.[Make a pass and obtain element with smallest value]
Repeat for i=pass+1,pass+2,….n.
If k[i] < k[minindex]
    then minindex <--- i.

4.[Exchange the elements]
If minindex!=pass
    then k[pass] interchange with k[minindex].


Algorithm for Bubble Sort

1.Initialize last <--- N.

2.[Loop on pass index]
Repeat through step 5 for pass=1,2…n-1.

3.[Initialize exchange ctr for this pass]
exchs <--- 0.

4.[Perform pair wise comparison on unsorted elements]
Repeat for i=1,2,….last - 1.
If k[i] > k[I+1]
then interchange both of them.
   exchs <--- exchs + 1.

5.[Check for Exchanges]
If exchs=0
then return [mission complete early]
    last <--- last – 1.


Algorithm for Merge Sort

i <--- first
j <--- second
k <--- 0.

2.[Compare corresponding element and output smallest]
while i<second and j>=third
if k[i] <= k[j]
then l <--- l + 1
        s[l] <--- k[i]
        i <--- i + 1
l <--- l + 1
s[l] <--- k[j]
j <--- j + 1.

3.[Copy the remaining elements]
if i >=second
then repeat while j<=third
l <--- l + 1
s[l] <--- k[j]
j <---- j + 1.
repeat while i<second
l <--- l + 1
s[l] <--- k[i]
i <---- i + 1.

Algorithm for Quick Sort

g <--- lb + 1
s <--- ub
flag <--- 0 
key <--- sortarray [lb]

2.[Check we have single element array or not]
if lb < ub
     [Repeat until key value is position at its final position]
     while flag =0

          [Position g no greater than key]
Repeat while sortarray [g] < key
Increment g by 1.

     Repeat while sortarray [s] > key
     Decrement s by 1.

[Check whether s is pointing to lower position]
if g < s
[Exchange values of g and s]
flag = 1
[Exchange the s with key position]

Call quicksort (sortarray,lb,s-1)
Call quicksort (sortarray,s+1,ub)

Algorithm for Insertion Sort

key <--- 1

2.[Following loop makes the elements sortarray [0] through sortarray [key] in order by inserting the element sortarray [key] at its pos. initially sortarray [0] may be through of as sorted array].

Repeat while key < size
temp <--- sortarray [key]
ctr <--- key – 1

Repeat while ctr >=0 and tamp <sortarray [ctr]
sortarray [ctr+1] <--- sortarray [ctr]
sortarray [ctr+1] <--- temp


Luisa Fischer
Luisa Fischer author of Algorithms of selection sort, bubble sort, merge sort, quick sort and insertion sort is from Frankfurt, Germany.
View All Articles

Please enter your Comment

  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].

No Comment Found, Be the First to post comment!