Searching and Sorting Arrays
Searching and Sorting Arrays
Programming
(CS-110)
Course Instructors:
Dr. Momina Moetesum
Ms. Shakeela Bibi
1
For Smaller Arrays (<10,000 Elements)
• Bubble Sort
• Selection Sort
• Insertion Sort
Sorting an
Array For Larger Arrays (>10,000 Elements)
• Quick Sort
• Merge Sort
• Radix Sort
• Heap Sort
2
Bubble Sort
• traverse from left and compare
adjacent elements and the higher
one is placed at right side.
• In this way, the largest element is
moved to the rightmost end at
first.
• This process is then continued to
find the second largest and place it
and so on until the data is sorted.
3
Bubble Sort
4
Optimized Bubble Sort
void bubbleSort(int arr[], int n) {
bool isUnsorted;
do {
isUnsorted = false;
for (int i = 0; i < (n - 1); i++) {
if (arr[i] > arr[i + 1]) {
isUnsorted = true;
for (; i < (n - 1); i++) {
if (arr[i] > arr[i + 1]) {
std::swap(arr[i], arr[i + 1]);
}
}
}
}
} while (isUnsorted);
}
5
Searching an Array
Every element is considered as a potential match for the key and checked for
the same.
If any element is found equal to the key, the search is successful and the index
of that element is returned.
If no element is found equal to the key, the search yields “No match found”.
7
Linear Search
// Driver code
int main(void)
// C++ code to linearly search x in arr[]. {
int arr[] = { 2, 3, 4, 10, 40 };
#include <bits/stdc++.h> int x = 10;
using namespace std; int N = sizeof(arr) / sizeof(arr[0]);
8
Binary Search
• Compare the middle element of the search
space with the key.
• If the key is found at middle element, the
process is terminated.
• If the key is not found at middle element,
choose which half will be used as the next
search space.
• If the key is smaller than the middle
element, then the left side is used for next
search.
• If the key is larger than the middle
element, then the right side is used for
next search.
• This process is continued until the key is found
or the total search space is exhausted.
9
Binary Search Algorithm
1.Start
2.Take input array and Target
3.Initialise start = 0 and end = (array size -1)
4.Intialise mid variable
5.mid = (start+end)/2
6.if array[ mid ] == target then return mid
7.if array[ mid ] < target then start = mid+1
8.if array[ mid ] > target then end = mid-1
9.if start<=end then goto step 5
10.return -1 as Not element found
11.Exit
10
// C++ program to implement iterative Binary Search
#include <iostream>
Iterative Solution using namespace std;
13