用C實現撲克牌排序

lt發表於2012-11-29
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 52
int main()
{
  int i,j;
  int a[N];
  char b[4][5]={"黑桃","紅桃","梅花","方片"};
  char c[13][3]={"2","3","4","5","6","7","8","9","10","J","Q","K","A"};
  int t; //用於交換值
  int p; //用於記錄位置
  for(i=0;i<N;i++)//初始化
    a[i]=i;
  for(i=0;i<N;i++)//隨機洗牌
  {
    srand((unsigned) time(NULL));
    p=rand()%(N-i);//將隨機範圍不斷縮小
    t=a[p]; 
    a[p]=a[N-i-1];
    a[N-i-1]=t;
  }
  printf("\n排序前\n");
  for(i=0;i<N;i++)//排序前輸出
    printf("%s %s\n",b[a[i]/13],c[a[i]%13]);

  for(i=0;i<N;i++)//排序
  for(j=0;j<N;j++)
  if(a[i]<a[j])
  {
    t=a[i];
    a[i]=a[j];
    a[j]=t;
  }
  printf("\n排序後\n");
  for(i=0;i<N;i++)//排序後輸出
    printf("%s %s\n",b[a[i]/13],c[a[i]%13]);

return 0;
}

相關文章