Bubble sort and Selection Sort
Sorting in C – Notes
What is Sorting?
Sorting is the process of arranging data in ascending or descending order.
Sorting makes searching faster and helps organize data efficiently.
Bubble Sort Algorithm
Definition
Bubble Sort is a simple sorting algorithm that:
-
Compares adjacent elements one by one
-
Swaps them if they are in the wrong order
-
Repeats until no swaps are needed
It is called bubble sort because smaller elements “bubble” to the top.
Working (Ascending Order)
-
Compare 1st and 2nd elements → swap if needed
-
Compare 2nd and 3rd → swap if needed
-
Continue till end of array
-
Repeat process n−1 times
-
Stop early if no swaps occur in a pass
Algorithm for Bubble Sort (Ascending Order)
-
Start
-
Read the number of elements n
-
Read the array elements
-
Repeat for i = 0 to n − 2
-
Set flag = 0 (to check if swapping happens)
-
For j = 0 to n − i − 2
-
If arr[j] > arr[j+1]
-
Swap arr[j] and arr[j+1]
-
Set flag = 1
-
-
-
If flag == 0, break (array already sorted)
-
-
Print the sorted array
-
Stop
Example Trace
Input array: [5, 3, 1, 7, 9]
Pass 1:
5↔3 → [3,5,1,7,9]
5↔1 → [3,1,5,7,9]
Pass 2:
3↔1 → [1,3,5,7,9]
Pass 3:
No swaps → Stop
Final result: [1,3,5,7,9]
Bubble Sort Function
Bubble Sort with Flag Optimization
Bubble Sort – Simple Program
Selection Sort
Definition
Selection Sort works by:
-
Dividing array into sorted and unsorted parts
-
Finding the minimum element from unsorted part
-
Swapping it with first unsorted element
Algorithm for Selection Sort (Ascending Order)
-
Start
-
Read the number of elements n
-
Read the array elements
-
For i = 0 to n − 2
-
Assume the current position is the minimum: min = i
-
For j = i + 1 to n − 1
-
If arr[j] < arr[min], then set min = j
-
-
If min ≠ i, swap arr[i] and arr[min]
-
-
Repeat until the array is sorted
-
Print the sorted array
-
Stop
Selection Sort Function
Selection Sort – Simple Program
Bubble Sort + Count Unique & Duplicate Numbers
Sorting Strings Alphabetically (Using strcmp & strcpy)
Comments
Post a Comment