Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <fstream>
- #include <cmath>
- #include <ctime>
- #include <stdlib.h>
- using namespace std;
- void HoanVi(int &x, int &y) {
- int temp = x;
- x = y;
- y = temp;
- }
- // Hàm phát sinh mảng dữ liệu ngẫu nhiên
- void GenerateRandomData(int a[], int n)
- {
- srand((unsigned int)time(NULL));
- for (int i = 0; i < n; i++)
- {
- a[i] = rand()%n;
- }
- }
- // Hàm phát sinh mảng dữ liệu có thứ tự tăng dần
- void GenerateSortedData(int a[], int n)
- {
- for (int i = 0; i < n; i++)
- {
- a[i] = i;
- }
- }
- // Hàm phát sinh mảng dữ liệu có thứ tự ngược (giảm dần)
- void GenerateReverseData(int a[], int n)
- {
- for (int i = 0; i < n; i++)
- {
- a[i] = n - 1 - i;
- }
- }
- // Hàm phát sinh mảng dữ liệu gần như có thứ tự
- void GenerateNearlySortedData(int a[], int n)
- {
- for (int i = 0; i < n; i++)
- {
- a[i] = i;
- }
- srand((unsigned int) time(NULL));
- for (int i = 0; i < 10; i ++)
- {
- int r1 = rand()%n;
- int r2 = rand()%n;
- HoanVi(a[r1], a[r2]);
- }
- }
- void GenerateData(int a[], int n, int dataType)
- {
- switch (dataType)
- {
- case 0: // ngẫu nhiên
- GenerateRandomData(a, n);
- break;
- case 1: // có thứ tự
- GenerateSortedData(a, n);
- break;
- case 2: // có thứ tự ngược
- GenerateReverseData(a, n);
- break;
- case 3: // gần như có thứ tự
- GenerateNearlySortedData(a, n);
- break;
- default:
- printf("Error: unknown data type!\n");
- }
- }
- void selectionSort(int arr[], int n) {
- int i, j, min_idx;
- for (i = 0; i < n-1; i++) {
- min_idx = i;
- for (j = i+1; j < n; j++)
- if (arr[j] < arr[min_idx])
- min_idx = j;
- HoanVi(arr[min_idx], arr[i]);
- }
- }
- void insertionSort(int arr[], int n)
- {
- int i, key, j;
- for (i = 1; i < n; i++)
- {
- key = arr[i];
- j = i - 1;
- /* Move elements of arr[0..i-1], that are
- greater than key, to one position ahead
- of their current position */
- while (j >= 0 && arr[j] > key)
- {
- arr[j + 1] = arr[j];
- j = j - 1;
- }
- arr[j + 1] = key;
- }
- }
- int main() {
- const int n = 100000;
- int a[n];
- GenerateData(a, n, 0);
- ofstream f("output.dat");
- f << n;
- for(int i = 0; i < n; i++) {
- f << a[i] << " ";
- }
- f << "\n";
- clock_t tStart = clock();
- insertionSort(a, n);
- printf("Time taken: %.9fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);
- for(int i = 0; i < n; i++) {
- f << a[i] << " ";
- }
- f << "\n";
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement