Thứ Ba, 1 tháng 12, 2015

Share code C - Mô phỏng thuật toán Interchange Sort bằng code C thường

Sau một thời gian tìm tòi, thì mình đã chịch nó thành công =))) sẽ update thêm các mô phỏng thuật toán khác :v Còn đây là demo:


Lưu ý: Code này chỉ chạy được trên Borland C, còn lại các complier khác thì mình chưa test, riêng Visual Studio thì là ko được rồi đấy :D

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<dos.h>

void nhap(int a[])
{
 for(int i=0; i<10; i++)
    a[i]=random(9);
}

void xuat(int a[])
{
    for(int i=0; i<10; i++)
    printf("%5d",a[i]);
}

void swap(int &a, int &b)
{
 int c=a; a=b; b=c;
}

void IS(int a[])
{
 for(int i=0; i<9; i++)
   for(int j=i+1; j<10; j++)
    if(a[i]>a[j])
      {
      sleep(1);
      textcolor(LIGHTRED);
          gotoxy(24+i*5,10);
          printf(" ");
          gotoxy(24+i*5,8);
          cprintf("%d",a[i]);
          gotoxy(24+j*5,10);
          sleep(1);
          printf(" ");
          gotoxy(24+j*5,9);
          cprintf("%d",a[j]);

          int kc=(24+j*5)-(24+i*5);
          for(int k=1; k<=kc; k++)
          {
           textcolor(LIGHTRED);
            gotoxy((24+j*5)-k,9);
           cprintf("%d",a[j]);
            gotoxy((24+j*5)-k+1,9);
            printf(" ");
            gotoxy((24+i*5)+k,8);
            cprintf("%d",a[i]);
            gotoxy((24+i*5)+k-1,8);
            printf(" ");
            sleep(1);
          }
          gotoxy((24+j*5)-kc,9);
          printf(" ");
          gotoxy((24+i*5)+kc,8);
          printf(" ");
          swap(a[i],a[j]);
          gotoxy(20,10);
          xuat(a);
          sleep(1);
      }
}


void main(void)
{
 int a[10];
   gotoxy(20,10);
   nhap(a);
   xuat(a);
   IS(a);
   getch();
}


Không có nhận xét nào:

Đăng nhận xét