新人新气象,又一个学习C的新人来了。
冒泡排序,基础中的基础,原理不啰嗦了。
代码中display()为数组展示函数,sort_bubble()为直接实现排序,details()为带动画展示。
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <windows.h> 4 5 #define LENGTH 20 6 7 const WORD FORE_BLUE = FOREGROUND_BLUE|FOREGROUND_INTENSITY; 8 const WORD FORE_GREEN = FOREGROUND_GREEN|FOREGROUND_INTENSITY; 9 const WORD FORE_RED = FOREGROUND_RED|FOREGROUND_INTENSITY; 10 const WORD FORE_WHITE = FOREGROUND_RED | FOREGROUND_GREEN|FOREGROUND_BLUE; 11 12 void sort_bubble(int *a); 13 void display(int *a); 14 void details(int *a); 15 16 void display(int *a) 17 { 18 int i; 19 for (i=0;i<LENGTH;i++) 20 { 21 printf("%2d ",a[i]); 22 } 23 printf("\n"); 24 } 25 26 void sort_bubble(int *a) 27 { 28 int i,j,k,temp; 29 for (i=0;i<LENGTH-1;i++) 30 { 31 k=0; 32 for (j=0;j<LENGTH-i-1;j++) 33 { 34 if (a[j]>a[j+1]) 35 { 36 temp=a[j]; 37 a[j]=a[j+1]; 38 a[j+1]=temp; 39 k++; 40 } 41 42 } 43 if (k==0) 44 { 45 break; 46 } 47 } 48 } 49 int main() 50 { 51 int array[LENGTH]={20,62,30,50,80,37,40,22,55,44, 52 77,85,18,44,90,73,26,10,46,64}; 53 int array2[LENGTH]={20,62,30,50,80,37,40,22,55,44, 54 77,85,18,44,90,73,26,10,46,64}; 55 printf("Before sort:\n"); 56 display(array); 57 sort_bubble(array); 58 printf("Success sort:\n"); 59 display(array); 60 printf("Press to display details:\n"); 61 getch(); 62 details(array2); 63 getch(); 64 return 0; 65 } 66 67 void details(int *a) 68 { 69 int i,j,k,temp; 70 HANDLE outhandle=GetStdHandle(STD_OUTPUT_HANDLE); 71 COORD xy={0,0}; 72 xy.Y=5; 73 display(a); 74 for (i=0;i<LENGTH-1;i++) 75 { 76 k=0; 77 for (j=0;j<LENGTH-i-1;j++) 78 { 79 Sleep(100); 80 xy.X=j*3; 81 SetConsoleTextAttribute(outhandle, FORE_RED); 82 SetConsoleCursorPosition(outhandle,xy); 83 printf("%2d %2d",a[j],a[j+1]); 84 if (a[j]>a[j+1]) 85 { 86 temp=a[j]; 87 a[j]=a[j+1]; 88 a[j+1]=temp; 89 Sleep(100); 90 xy.X=j*3; 91 SetConsoleCursorPosition(outhandle,xy); 92 printf(" "); 93 SetConsoleCursorPosition(outhandle,xy); 94 printf("%2d %2d",a[j],a[j+1]); 95 k++; 96 } 97 Sleep(100); 98 xy.X=j*3; 99 SetConsoleCursorPosition(outhandle,xy); 100 SetConsoleTextAttribute(outhandle, FORE_WHITE); 101 printf("%2d %2d",a[j],a[j+1]); 102 } 103 xy.X=3*(LENGTH-1-i); 104 SetConsoleCursorPosition(outhandle,xy); 105 SetConsoleTextAttribute(outhandle, FORE_GREEN); 106 printf("%2d",a[LENGTH-i-1]); 107 if (k==0) 108 { 109 break; 110 } 111 } 112 xy.X=0; 113 xy.Y=5; 114 SetConsoleCursorPosition(outhandle,xy); 115 SetConsoleTextAttribute(outhandle, FORE_GREEN); 116 display(a); 117 CloseHandle(outhandle); 118 }