Sortiranje(InsertionSort)

Algoritam za sortiranje niza uz pomoć InsertionSort-a.Niz se sastoji od 5 elemenata,koji se popunjuju sa slučajnim brojevima 1-1000.

#include <iostream>
using namespace std;
#include <cstdlib>
#include <ctime>
// Insertion Sort
int main() {
int i, j, kljuc, a[5];
// niz se sastoji od 5 random brojeva 1-1000

// seed za random brojeve
srand(time(NULL));
cout << "Niz prije sortiranja: " << endl;
for (i = 0; i < 5; i++) {
a[i] = rand() % 1000;
cout << a[i] << " ";
}
cout << endl;
cout << endl;
// element po element idemo kroz niz te ga stavljamo na odgovarajuce mjesto
for (j = 1; j < 5; j++) {
kljuc = a[j];
for (i = j - 1; (i >= 0) && (a[i] > kljuc); i--) {
a[i + 1] = a[i];
}
a[i + 1] = kljuc;
}

cout << "Niz nakon sortiranja: " << endl;
for (i = 0; i < 5; i++) {
cout << a[i] << " ";
}
cout << endl;
system("Pause");
return 0;
}

Capture

 

Komentariši