C語言實現冒泡排序演算法

來源:互聯網
上載者:User

標籤:ext   array   ++   let   圖片   src   win   數組   函數   

新人新氣象,又一個學習C的新人來了。

冒泡排序,基礎中的基礎,原理不囉嗦了。

代碼中display()為數組展示函數,sort_bubble()為直接實現排序,details()為帶動畫展示。

虛擬碼:

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>

#define LENGTH 20

const WORD FORE_BLUE = FOREGROUND_BLUE|FOREGROUND_INTENSITY;
const WORD FORE_GREEN = FOREGROUND_GREEN|FOREGROUND_INTENSITY;
const WORD FORE_RED = FOREGROUND_RED|FOREGROUND_INTENSITY;
const WORD FORE_WHITE = FOREGROUND_RED | FOREGROUND_GREEN|FOREGROUND_BLUE;

void sort_bubble(int *a);
void display(int *a);
void details(int *a);

void display(int *a)
{
int i;
for (i=0;i<LENGTH;i++)
{
printf("%2d ",a[i]);
}
printf("\n");
}

void sort_bubble(int *a)
{
int i,j,k,temp;
for (i=0;i<LENGTH-1;i++)
{
k=0;
for (j=0;j<LENGTH-i-1;j++)
{
if (a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
k++;
}

}
if (k==0)
{
break;
}
}
}
int main()
{
int array[LENGTH]={20,62,30,50,80,37,40,22,55,44,
77,85,18,44,90,73,26,10,46,64};
int array2[LENGTH]={20,62,30,50,80,37,40,22,55,44,
77,85,18,44,90,73,26,10,46,64};
printf("Before sort:\n");
display(array);
sort_bubble(array);
printf("Success sort:\n");
display(array);
printf("Press to display details:\n");
getch();
details(array2);
getch();
return 0;
}

void details(int *a)
{
int i,j,k,temp;
HANDLE outhandle=GetStdHandle(STD_OUTPUT_HANDLE);
COORD xy={0,0};
xy.Y=5;
display(a);
for (i=0;i<LENGTH-1;i++)
{
k=0;
for (j=0;j<LENGTH-i-1;j++)
{
Sleep(100);
xy.X=j*3;
SetConsoleTextAttribute(outhandle, FORE_RED);
SetConsoleCursorPosition(outhandle,xy);
printf("%2d %2d",a[j],a[j+1]);
if (a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
Sleep(100);
xy.X=j*3;
SetConsoleCursorPosition(outhandle,xy);
printf(" ");
SetConsoleCursorPosition(outhandle,xy);
printf("%2d %2d",a[j],a[j+1]);
k++;
}
Sleep(100);
xy.X=j*3;
SetConsoleCursorPosition(outhandle,xy);
SetConsoleTextAttribute(outhandle, FORE_WHITE);
printf("%2d %2d",a[j],a[j+1]);
}
xy.X=3*(LENGTH-1-i);
SetConsoleCursorPosition(outhandle,xy);
SetConsoleTextAttribute(outhandle, FORE_GREEN);
printf("%2d",a[LENGTH-i-1]);
if (k==0)
{
break;
}
}
xy.X=0;
xy.Y=5;
SetConsoleCursorPosition(outhandle,xy);
SetConsoleTextAttribute(outhandle, FORE_GREEN);
display(a);
CloseHandle(outhandle);
}

C語言實現冒泡排序演算法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.