bubbl-sort OK, and OOP of template OK
(高顯忠, sjgau4311@gmail.com, 2010-12-22 08:41)
1樓
#include <cstdlib>
#include <iostream>
// ----------------------------------------------
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <math.h>
// ----------------------------------------------
using namespace std;
// ----------------------------------------------
// swap_int( &a[j], &a[k]);
void swap_int(int *x, int *y)
{
int temp;
temp= (*x);
(*x)= (*y);
(*y)= temp;
}// end of swap_int()
// ----------------------------------------------
// swap_2(a[j], a[k]);
template <class T>
swap_2(T &x, T &y)
{
T temp;
temp= x;
x= y;
y= temp;
}// end of swap_2()
// ----------------------------------------------
// show_data(a, no);
void show_data(int a[], int no)
{
int i;
printf("\n");
for (i=0;i<no;i++) {
printf("%3d, ", a[i]);
}
printf("\n");
system("pause");
}// end of show_data()
// ----------------------------------------------
int main(int argc, char *argv[])
{
int no, a[100], i;
// for bubble- sort
no= 10;
srand((unsigned int) time(NULL));
srand(123);
printf("\n");
for (i=0;i<no;i++) {
a[i]= rand()%100;
printf("%3d, ", a[i]);
}
printf("\n");
system("pause");
// ------------------------------------------
int j, k, flag;
for (i=0;i<no;i++) {
flag= 0;
for (j=0;j<=(no-2);j++) {
k= j+1;
// a[j] <= a[k]
if (a[j] > a[k]) {
// swap_int(&a[j], &a[k]);
swap_2(a[j], a[k]);
flag= 1;
}
}
printf("\n i= %d, flag= %d\n", i, flag);
show_data(a, no);
if (flag == 0) break;
}
return EXIT_SUCCESS;
}
// ----------------------------------------------
#if 0
40, 53, 75, 4, 63, 65, 49, 78, 60, 64,
請按任意鍵繼續 . . .
i= 0, flag= 1
40, 53, 4, 63, 65, 49, 75, 60, 64, 78,
請按任意鍵繼續 . . .
i= 1, flag= 1
40, 4, 53, 63, 49, 65, 60, 64, 75, 78,
請按任意鍵繼續 . . .
i= 2, flag= 1
4, 40, 53, 49, 63, 60, 64, 65, 75, 78,
請按任意鍵繼續 . . .
i= 3, flag= 1
4, 40, 49, 53, 60, 63, 64, 65, 75, 78,
請按任意鍵繼續 . . .
i= 4, flag= 0
4, 40, 49, 53, 60, 63, 64, 65, 75, 78,
請按任意鍵繼續 . . .
Press any key to continue
#endif
// ----------------------------------------------