9,10,11. Searching and Sorting
9,10,11. Searching and Sorting
Tushar B. Kute,
http://tusharkute.com
Searching Algorithms
end procedure
Complexity
• We change our low to mid + 1 and find the new mid value
again.
low = mid + 1
mid = low + (high - low) / 2
Binary Search
• end procedure
• set midPoint = lowerBound +
( upperBound - lowerBound ) / 2
Complexity
• Time Complexity
– The time complexity of binary search is O(log n),
where n is the number of elements in the sorted
array.
– This means that the number of comparisons required
to find an element in the array grows logarithmically
with the size of the array.
Sorting Algorithms
• Selection Sort
• Insertion Sort
• Bubble Sort
• Quick Sort
• Heap Sort
• Merge Sort
Selection Sort
• Advantages
– Selection sort is a simple and easy-to-implement
sorting algorithm. It is also a stable sorting
algorithm, which means that it preserves the
original order of equal elements in the array.
• Disadvantages
– Selection sort is a very inefficient sorting
algorithm, with a time complexity of O(n^2). It is
not recommended for sorting large arrays.
Insertion Sort
• insertionSort(array)
• mark first element as sorted
• for each unsorted element X
• 'extract' the element X
• for j <- lastSortedIndex down to 0
• if current element j > X
• move sorted element to the right by 1
• break loop and insert X here
• end insertionSort
Insertion Sort
Insertion Sort
Insertion Sort
Insertion Sort
Insertion Sort
Bubble Sort
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
Bubble Sort Pseudo-code
• procedure bubbleSort( list : array of items )
• loop = list.count;
• for i = 0 to loop-1 do:
• swapped = false
• for j = 0 to loop-1 do:
• /* compare the adjacent elements */
• if list[j] > list[j+1] then
• /* swap them */
• swap( list[j], list[j+1] )
• swapped = true
• end if
• end for
• /*if no number was swapped that means
• array is sorted now, break the loop.*/
• if(not swapped) then
• break
• end if
• end for
• end procedure return list
Quick Sort
• After the final merging, the list should look like this −
Web Resources
https://mitu.co.in
@mituskillologies http://tusharkute.com @mituskillologies