You are on page 1of 29

SORTING

Sorting
Sorting is any process of arranging items systematically, and has two
common, yet distinct meanings:
• Ordering: arranging items in a sequence ordered by some criterion
• Categorizing: grouping items with similar properties.
Sorting (cont.)
Following are some of the examples of sorting in real-life scenarios
Telephone Directory − The telephone directory stores the telephone
numbers of people sorted by their names, so that the names can be
searched easily.
Dictionary − The dictionary stores words in an alphabetical order so
that searching of any word becomes easy.
Common Sorting Technique
• Bubble/Shell sort : Exchange two adjacent elements if they are out of order.
Repeat until array is sorted.
• Insertion sort : Scan successive elements for an out-of-order item, then insert
the item in the proper place.
• Selection sort : Find the smallest (or biggest) element in the array, and put it
in the proper place. Swap it with the value in the first position. Repeat until
array is sorted.
• Quick sort : Partition the array into two segments. In the first segment, all
elements are less than or equal to the pivot value. In the second segment, all
elements are greater than or equal to the pivot value. Finally, sort the two
segments recursively.
• Merge sort : Divide the list of elements in two parts, sort the two parts
individually and then merge it.
Bubble sort
Bubble sort is based on the idea of repeatedly comparing pairs of
adjacent elements and then swapping their positions if they exist in the
wrong order.
Example
Algorithm
• We assume list is an array of n elements.
• We further assume that swap function swaps the values of the given array elements
• begin BubbleSort(list)
• for all elements of list
• if list[i] > list[i+1]
• swap(list[i], list[i+1])
• end if
• end for
• return list
• end BubbleSort
Task : 1
• Write C/C++ code for LINER and BINARY search.
• Write a C/C++ program for BUBBLE sort.
Problem: 56 , 91 , 35, 72, 48, 68
Insertion Sort
• Insertion sort is based on the idea that one element from the input
elements is consumed in each iteration to find its correct position
• i.e. the position to which it belongs in a sorted array.
• It iterates the input elements by growing the sorted array at each
iteration
• It compares the current element with the largest value in the sorted
array.
Insertion Sort (cont.)
• If the current element is greater, then it leaves the element in its
place and moves on to the next element else it finds its correct position
in the sorted array and moves it to that position.
• This is done by shifting all the elements, which are larger than the
current element, in the sorted array to one position ahead.
Example
Algorithm
Task : 2
• Write code for INSERTION sort.
Quick Sort
• Assignment [included in exams]

You might also like