Introduction
This project focuses on comparing three basic sorting algorithms: Bubble Sort, Selection
Sort, and Insertion Sort. To analyze their performance, 1000 random numbers are generated
and sorted using each algorithm. The execution time is measured before and after each
sorting process to determine which algorithm performs more efficiently. This helps us
understand how different sorting techniques behave with the same dataset.
Execution Code
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <chrono>
using namespace std;
using namespace std::chrono;
void bubbleSort(vector<int>& arr) {
int n = [Link]();
for (int i = 0; i < n - 1; i++)
for (int j = 0; j < n - i - 1; j++)
if (arr[j] > arr[j + 1])
swap(arr[j], arr[j + 1]);
}
void selectionSort(vector<int>& arr) {
int n = [Link]();
for (int i = 0; i < n - 1; i++) {
int minIdx = i;
for (int j = i + 1; j < n; j++)
if (arr[j] < arr[minIdx])
minIdx = j;
swap(arr[i], arr[minIdx]);
}
}
void insertionSort(vector<int>& arr) {
int n = [Link]();
for (int i = 1; i < n; i++) {
int key = arr[i], j = i - 1;
while (j >= 0 && arr[j] > key)
arr[j + 1] = arr[j--];
arr[j + 1] = key;
}
}
double measureTime(void (*sortFunc)(vector<int>&), vector<int> arr) {
auto start = high_resolution_clock::now();
sortFunc(arr);
auto end = high_resolution_clock::now();
return duration<double>(end - start).count();
}
int main() {
srand(time(0));
vector<int> data(1000);
for (int i = 0; i < 1000; i++) {
data[i] = rand() % 10000;
}
cout << "Bubble Sort: " << measureTime(bubbleSort, data) << " seconds\n";
cout << "Selection Sort: " << measureTime(selectionSort, data) << " seconds\n";
cout << "Insertion Sort: " << measureTime(insertionSort, data) << " seconds\n";
return 0;
}
Input: Auto generated 1000’s of data.
Output:
Bubble Sort: 0.008387 seconds
Selection Sort: 0.002453 seconds
Insertion Sort: 5.6e-05 seconds
Conclusion
The results show that Insertion Sort performed the fastest, followed by Selection Sort, while
Bubble Sort was the slowest. Therefore, among the three algorithms tested, Insertion Sort is
the most efficient for this dataset.