Untitled
unknown
plain_text
2 years ago
1.6 kB
7
Indexable
#include <iostream>
#include <fstream>
#include <chrono> // For measuring time
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
std::swap(arr[j], arr[j+1]);
}
}
}
}
int main() {
// Open a file for writing
std::ofstream outFile("elements.txt");
if (!outFile) {
std::cerr << "Error creating file." << std::endl;
return 1;
}
int n;
std::cout << "Enter the number of elements: ";
std::cin >> n;
int arr[n];
for (int i = 0; i < n; i++) {
std::cout << "Enter element " << i + 1 << ": ";
std::cin >> arr[i];
outFile << arr[i] << " ";
}
outFile.close();
// Display unsorted elements
std::cout << "Unsorted elements: ";
for (int i = 0; i < n; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
// Measure time taken for bubble sort
auto start = std::chrono::high_resolution_clock::now();
bubbleSort(arr, n);
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
// Display sorted elements
std::cout << "Sorted elements: ";
for (int i = 0; i < n; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
// Display time taken
std::cout << "Time taken by bubble sort: " << duration.count() << " microseconds" << std::endl;
return 0;
}Editor is loading...