1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
| #include <iostream>
#include <ctime>
#include <cstdlib>
#include <cstdio>
using namespace std;
void fusion (int *a, int n, int m)
{
int i, j, k;
int * x = new int [n];
for (i = 0, j = m, k = 0; k < n; k++) {
x[k] = j == n ? a[i++]
: i == m ? a[j++]
: a[j] < a[i] ? a[j++]
: a[i++];
}
for (i = 0; i < n; i++) {
a[i] = x[i];
}
delete(x);
}
void tri_fusion (int *liste, int taille) {
if (taille < 2) return;
int milieu = taille / 2;
tri_fusion(liste, milieu);
tri_fusion(liste- milieu, taille - milieu);
fusion(liste, taille, milieu);
}
void tri_bulle(int* tableau,int x)
{
int passage = 0;
bool permutation = true;
int en_cours;
while ( permutation) {
permutation = false;
passage ++;
for (en_cours=0;en_cours<x-passage;en_cours++) {
if (tableau[en_cours]>tableau[en_cours+1]){
permutation = true;
// on echange les deux elements
int temp = tableau[en_cours];
tableau[en_cours] = tableau[en_cours+1];
tableau[en_cours+1] = temp;
}
}
}
}
void tri_insertion(int* t,int x)
{
int i, j;
int en_cours;
for (i = 1; i < x; i++) {
en_cours = t[i];
for (j = i; j > 0 && t[j - 1] > en_cours; j--) {
t[j] = t[j - 1];
}
t[j] = en_cours;
}
}
void tri_rapide (int *tableau, int taille) {
int mur, courant, pivot, tmp;
if (taille < 2) return;
// On prend comme pivot l element le plus a droite
pivot = tableau[taille - 1];
mur = courant = 0;
while (courant<taille) {
if (tableau[courant] <= pivot) {
if (mur != courant) {
tmp=tableau[courant];
tableau[courant]=tableau[mur];
tableau[mur]=tmp;
}
mur ++;
}
courant ++;
}
tri_rapide(tableau, mur - 1);
tri_rapide(tableau + mur - 1, taille - mur + 1);
}
void affiche(int* tableau,int x)
{
for (int i=0;i<x;i++)
{
cout<<" "<<tableau[i]<<" ";
}
cout<<endl;
cout<<endl;
}
int * RandomArray(int n)
{
srand(time(NULL));
int *tab=new int [n];
for (int i=0;i<n;i++)
{
tab[i]=(rand()%n);
}
return tab;
}
int main()
{
int n=0;
while (n<=5 || n>=500000 )
{
cout<<"entrer une valeur entre 5 et 500000 : "<<endl;
cin >>n;
}
int *arrays = RandomArray(n);
affiche (arrays, n);
cout<<"tri bulle"<<endl;
tri_bulle(arrays, n);
affiche (arrays, n);
int *arrays1 = RandomArray(n);
affiche (arrays1, n);
cout<<"tri insertion"<<endl;
tri_insertion(arrays1, n);
affiche (arrays1, n);
int *arrays2 = RandomArray(n);
affiche (arrays2, n);
cout<<"tri rapide"<<endl;
// tri_rapide(arrays2, n);
affiche (arrays2, n);
int *arrays3 = RandomArray(n);
affiche (arrays3, n);
cout<<"tri fusion"<<endl;
tri_fusion(arrays3, n);
// affiche (arrays3, n);
} |
Partager