Thursday, May 10, 2012

example program sorting

# Include <iostream># Include <conio.h>
int data [100], data2 [100];int n;
void exchange (int a, int b){int t;t = data [b];data [b] = data [a];data [a] = t;}
bubble_sort void (){for (int i = 1; i <n; i + +){for (int j = n-1; j> = i; j -){if (data [j] <data [j-1]) exchange (j, j-1);}}cout << "bubble sort is complete!" << endl;}
exchange_sort void (){for (int i = 0; i <n-1; i + +){for (int j = (i +1); j <n; j + +){if (data [i]> data [j]) Swap (i, j);}}cout << "exchange sort is complete!" << endl;}
selection_sort void (){int pos, i, j;for (i = 0; i <n-1; i + +){pos = i;for (j = i +1; j <n; j + +){if (data [j] <data [post]) pos = j;}if (post! = i) exchange (post, i);}cout << "selection sort is complete!" << endl;}
insertion_sort void (){int temp, i, j;for (i = 1; i <n; i + +){temp = data [i];j = i -1;while (data [j]> temp && j> = 0){data [j +1] = data [j];j -;}data [j +1] = temp;}cout << "insertion sort is complete!" << endl;}
void QuickSort (int L, int R) / / sort the best I've ever had :){int i, j;int mid;
i = L;j = R;mid = data [(L + R) / 2];
do{while (data [i] <mid) i + +;while (data [j]> mid) j -;
if (i <= j){exchange (i, j);i + +;j -;};} While (i <j);
if (l <j) QuickSort (L, j);if (i <R) QuickSort (i, R);}

void Input (){cout << "Enter the number of data ="; cin >> n;for (int i = 0; i <n; i + +){cout << "Enter data into the" << (i +1) << "="; cin >> data [i];data2 [i] = data [i];}}
void Show (){cout << "Data:" << endl;for (int i = 0; i <n; i + +){cout << data [i] << "";}cout << endl;}
AcakLagi void (){for (int i = 0; i <n; i + +){data [i] = data2 [i];}cout << "The data is scrambled!" << endl;}
void main (){int a pill;clrscr ();do{clrscr ();cout << "Sorting Program!" << endl;cout << "*********************************************" << endl;cout << "1. Input Data" << endl;cout << "2. Bubble Sort" << endl;cout << "3. Exchange Sort" << endl;cout << "4. Selection Sort" << endl;cout << "5. Insertion Sort" << endl;cout << "6. Quick Sort" << endl;cout << "7. Show Data" << endl;cout << "8. Random Data" << endl;cout << "9. Exit" << endl;cout << "Your choice:"; cin >> pill;switch (pill){case 1: Input (); break;case 2: bubble_sort (); break;case 3: exchange_sort (); break;case 4: selection_sort (); break;case 5: insertion_sort (); break;case 6: QuickSort (0, n-1);cout << "quick sort is complete!" << endl;break;case 7: Display (); break;case 8: AcakLagi (); break;}getch ();} While (pil! = 9);}

No comments:

Post a Comment