[go: up one dir, main page]

0% found this document useful (0 votes)
1 views2 pages

Selection Sort

The document contains a C++ program that implements the Selection Sort algorithm to sort an array of integers. It prompts the user to input the size and elements of the array, sorts the array using Selection Sort, and measures the execution time in nanoseconds. Finally, it prints the sorted array and cleans up the dynamically allocated memory.

Uploaded by

kimajam628
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views2 pages

Selection Sort

The document contains a C++ program that implements the Selection Sort algorithm to sort an array of integers. It prompts the user to input the size and elements of the array, sorts the array using Selection Sort, and measures the execution time in nanoseconds. Finally, it prints the sorted array and cleans up the dynamically allocated memory.

Uploaded by

kimajam628
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <iostream>

#include <chrono>
using namespace std;
using namespace std::chrono;

// Selection Sort function


void selectionSort(int arr[], int size) {
for (int i = 0; i < size - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < size; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// Swap the found minimum element with the first element of unsorted
portion
if (minIndex != i) {
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
}

// Function to print the array


void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}

int main() {
int size;
cout << "Enter the size of the array: ";
cin >> size;

int* arr = new int[size];


cout << "Enter " << size << " elements: ";
for (int i = 0; i < size; i++) {
cin >> arr[i];
}

cout << "Original array: ";


printArray(arr, size);

// Measure execution time


auto start = high_resolution_clock::now();
selectionSort(arr, size);
auto end = high_resolution_clock::now();
auto duration = duration_cast<nanoseconds>(end - start);

cout << "Sorted array: ";


printArray(arr, size);
cout << "Execution time: " << duration.count() << " nanoseconds" << endl;

// Clean up dynamic memory


delete[] arr;
return 0;
}

You might also like