Data Structures and Algorithms (CS F211) Sorting
Data Structures and Algorithms (CS F211) Sorting
Sorting
Sarthak Moorjani, Samarth Jain
Spring 2019
1 Sorting Techniques
1.1 Selection Sort
The basic idea of selection sorts lies behind the fact that it finds the minimum
element in each iteration (of the unsorted array) and puts the minimum element
into its correct location. The process repeats and finally we get the sorted array.
Technically speaking, every element is compared to every other element and the
time complexity of the algorithm is O(N 2 ). Following is the pseudo-code for
selection sort -
v o i d s e l e c t i o n s o r t ( i n t A[ ] , i n t n ) {
i n t min ;
f o r ( i n t i = 0 ; i < n−1 ; i ++) { .
minimum = i ;
f o r ( i n t j = i +1; j < n ; j++ ) {
i f (A[ j ] < A[ min ] ) {
min = j ;
}
}
swap ( A[ min ] , A[ i ] ) ;
}
If you want, you can try practicing the code here.
1
Following is the pseudocode for bubble sort -
v o i d b u b b l e s o r t ( i n t A[ ] , i n t n ) {
i n t temp ;
f o r ( i n t k = 0 ; k< n−1; k++) {
f o r ( i n t i = 0 ; i < n−k −1; i ++) {
i f (A[ i ] > A[ i +1] ) {
temp = A[ i ] ;
A[ i ] = A[ i + 1 ] ;
A[ i +1] = temp ;
}
}
}
}
If you want, you can try practicing the code here.
2
1.4 Merge Sort
Merge sort is a divide-and-conquer algorithm based on the idea of breaking
down a list into several sub-lists until each sublist consists of a single element
and merging those sublists in a manner that results into a sorted list.
Idea
• Take adjacent pairs of two singleton lists and merge them to form a list
of 2 elements. N will now convert into N2 lists of size 2.
• Repeat the process till a single sorted list of obtained.
The pseudo-code of the main divide and conquer function of merge sort is
as follows -
v o i d m e r g e s o r t ( i n t A[ ] , i n t s t a r t , i n t end )
{
i f ( s t a r t < end ) {
i n t mid = ( s t a r t + end ) / 2 ;
m e r g e s o r t (A, s t a r t , mid ) ;
m e r g e s o r t (A, mid+1 , end ) ;
merge (A, s t a r t , mid , end ) ;
}
}
Here the merge function simply merges the two arrays. It is important to
note that the time complexity of mergesort algorithm is always O(N logN ). It
is recommended that you try to code this atleast twice. You can try practicing
merge sort here.
3
Here is the pseudo-code for quicksort -
q u i c k s o r t (A, p , r ) {
i f ( p<r )
q = p a r t i t i o n (A, p , r )
q u i c k s o r t (A, p , q−1)
q u i c k s o r t (A, q+1, r )
}
p a r t i t i o n (A, p , r ) {
i = p−1
f o r ( i n t j=p ; j<=r −1; j ++}{
i f (A[ j ]<=A[ r ] ) {
i ++;
swap (A[ i ] ,A[ j ] )
}
}
swap (A[ i +1] ,A[ r ] )
r e t u r n i +1
}
2 Problems
• Bubble Sort related problem Problem Link
• Quick Sort related problem Problem Link
• Descending Sort Problem Link
• The Crofts Game Problem Link