闲来无事,研究了一个算法。这天气坐着都流汗。
1
# include
<
stdio.h
>
2 # define N 3
3
4 void swap( int arr[], int num1, int num2) {
5 int t = arr[num1];
6 arr[num1] = arr[num2];
7 arr[num2] = t;
8 }
9
10 void reverse( int arr[], int num1, int num2) {
11 int i;
12 for (i = 0 ; i < (num2 - num1) / 2 ; i ++ ) {
13 swap(arr, num1 + i, num2 - 1 - (i));
14 }
15 }
16
17 int nextArr( int arr[]) {
18 int left = - 1 ;
19 int right = - 1 ;
20 int i;
21 for (i = N - 1 ; i > 0 ; i -- ) {
22 if (arr[i - 1 ] < arr[i]) {
23 left = i - 1 ;
24 break ;
25 }
26 }
27 if (left < 0 ) {
28 return 0 ;
29 }
30
31
32 for (i = N - 1 ; i >= left; i -- ) {
33 if (arr[i] > arr[left]) {
34 right = i;
35 break ;
36 }
37 }
38 swap(arr, left, right);
39 reverse(arr, left + 1 , N);
40 return 1 ;
41 }
42
43 int sort( int arr[]){
44 int i,j,temp;
45 for (i = 0 ;i <= N;i ++ ){
46 for (j = 0 ;j < N - i;j ++ ){
47 if (arr[j] > arr[j + 1 ]){
48 temp = arr[j];
49 arr[j] = arr[j + 1 ];
50 arr[j + 1 ] = temp;
51 }
52 }
53 }
54 return arr[N];
55 }
56
57 void syarrange( int arr[]){
58 int i;
59 arr[N] = sort(arr);
60 do {
61 for (i = 0 ; i < N; i ++ ) {
62 printf( " %d " ,arr[i]);
63 }
64 printf( " \n " );
65 } while (nextArr(arr) == 1 );
66 }
67
68 int main(){
69 int arr[N] = { 3 , 1 , 2 };
70 syarrange(arr);
71 getchar();
72 return 0 ;
73 }
2 # define N 3
3
4 void swap( int arr[], int num1, int num2) {
5 int t = arr[num1];
6 arr[num1] = arr[num2];
7 arr[num2] = t;
8 }
9
10 void reverse( int arr[], int num1, int num2) {
11 int i;
12 for (i = 0 ; i < (num2 - num1) / 2 ; i ++ ) {
13 swap(arr, num1 + i, num2 - 1 - (i));
14 }
15 }
16
17 int nextArr( int arr[]) {
18 int left = - 1 ;
19 int right = - 1 ;
20 int i;
21 for (i = N - 1 ; i > 0 ; i -- ) {
22 if (arr[i - 1 ] < arr[i]) {
23 left = i - 1 ;
24 break ;
25 }
26 }
27 if (left < 0 ) {
28 return 0 ;
29 }
30
31
32 for (i = N - 1 ; i >= left; i -- ) {
33 if (arr[i] > arr[left]) {
34 right = i;
35 break ;
36 }
37 }
38 swap(arr, left, right);
39 reverse(arr, left + 1 , N);
40 return 1 ;
41 }
42
43 int sort( int arr[]){
44 int i,j,temp;
45 for (i = 0 ;i <= N;i ++ ){
46 for (j = 0 ;j < N - i;j ++ ){
47 if (arr[j] > arr[j + 1 ]){
48 temp = arr[j];
49 arr[j] = arr[j + 1 ];
50 arr[j + 1 ] = temp;
51 }
52 }
53 }
54 return arr[N];
55 }
56
57 void syarrange( int arr[]){
58 int i;
59 arr[N] = sort(arr);
60 do {
61 for (i = 0 ; i < N; i ++ ) {
62 printf( " %d " ,arr[i]);
63 }
64 printf( " \n " );
65 } while (nextArr(arr) == 1 );
66 }
67
68 int main(){
69 int arr[N] = { 3 , 1 , 2 };
70 syarrange(arr);
71 getchar();
72 return 0 ;
73 }