选择排序Selection sort

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #include<time.h>
 4 #define N 10
 5 int main()
 6 {
 7     int a[N], i, j, temp, b;
 8     srand(time(NULL));
 9     for(i=0;i<N;i++)
10         a[i]=rand()%100;
11     for(i=0;i<N;i++)
12         printf("%3d", a[i]);
13     printf("\n");
14     for(i=0;i<N-1;i++)
15     {
16         temp=i;
17         for(j=i+1;j<N;j++)
18         {
19             if(a[temp]>a[j])
20                 temp=j;
21         }
22         if(i!=temp)
23         {
24             b=a[temp];
25             a[temp]=a[i];
26             a[i]=b;
27         }
28     }
29     for(i=0;i<N;i++)
30         printf("%3d", a[i]);
31     printf("\n");
32     return 0;
33 }
 1 #include<iostream>
 2 #include<time.h>
 3 #include<iomanip>
 4 using namespace std;
 5 const int N=10;
 6 int main()
 7 {
 8     int a[N], i, j, temp, b;
 9     srand(time(NULL));
10     for(i=0;i<N;i++)
11         a[i]=rand()%100;
12     for(i=0;i<N;i++)
13         cout<<setw(3)<<a[i];
14     cout<<endl;
15     for(i=0;i<N-1;i++)
16     {
17         temp=i;
18         for(j=i+1;j<N;j++)
19         {
20             if(a[temp]>a[j])
21                 temp=j;
22         }
23         if(i!=temp)
24         {
25             b=a[temp];
26             a[temp]=a[i];
27             a[i]=b;
28         }
29     }
30     for(i=0;i<N;i++)
31         cout<<setw(3)<<a[i];
32     cout<<endl;
33 }

选择排序的熟练。

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #include<time.h>
 4 void selection_sort(int a[],int n);
 5 #define N 10
 6 int main()
 7 {
 8     int    a[N], i;
 9     srand(time(NULL));
10     for(i=0;i<N;i++)
11         a[i]=rand()%100;
12     for(i=0; i<N; i++)
13         printf("%3d", a[i]);
14     printf("\n");
15     selection_sort(a,N);
16     for(i=0; i<N; i++)
17         printf("%3d", a[i]);
18     printf("\n");
19 
20 }
21 
22 
23 void selection_sort(int a[],int n)
24 {
25     int i, j, temp, b;
26     for(i=0; i<n-1; i++)
27     {
28         temp=i;
29         for(j=i+1; j<n; j++)
30         {
31             if(a[temp]>a[j])
32                 temp=j;
33         }
34         if(i!=temp)
35         {
36             b=a[temp];
37             a[temp]=a[i];
38             a[i]=b;
39         }
40     }
41 }

 

posted @ 2013-06-07 19:07  Geekers  阅读(160)  评论(0编辑  收藏  举报