各种排序方法

冒泡排序法

#include
#include
#include

#define M 50

void BubbleSort(int a[], int n) {
  int i, j;
  int temp;

  for (i = 0; i < n - 1; i++) {
    for (j = 0; j < n - i - 1; j++) {
      temp = a[j];
      a[j] = a[j] < a[j + 1] ? a[j] : a[j + 1];
      if (a[j] != temp) {
        a[j + 1] = temp;
      }
    }
  }
}

int main(void) {
  int a[M];
  int i;
  srand((unsigned)time(NULL));
  for (i = 0; i < M; i++) {
  a[i] = rand() % 101;
  printf("%d ", a[i]);
  }
  printf("\n");
  BubbleSort(a,M);
  for (i = 0; i < M; i++) {
  printf("%d ",a[i]);
  }
  return 0;
}

选择排序法

#include
#include
#include

#define M 50

int *MinPointer(int a[], int n) {
  int *pMin;
  int i;
  pMin = &a[0];
  for (i = 0; i < n; i++) {
    if (*pMin > a[i]) {
      pMin = &a[i];
    }
  }
  return pMin;
}

void SelectionSort(int a[], int n) {
  int i, temp;
  int *pMin;
  for (i = 0; i < n - 1; i++) {
    pMin = MinPointer(&a[i], n - i);
    temp = a[i];
    a[i] = *pMin;
    *pMin = temp;
  }
}


int main(void) {
  int a[M];
  int i;
  srand((unsigned)time(NULL));
  for (i = 0; i < M; i++) {
  a[i] = rand() % 101;
  printf("%d ", a[i]);
  }
  printf("\n");
  SelectionSort(a,M);
  for (i = 0; i < M; i++) {
  printf("%d ",a[i]);
  }
  return 0;
}

链表排序法

#include 
#include
#include

typedef struct NODE {
  struct NODE *next;
  int value;
} Node;

typedef enum { ERROR = 0, OK = 1 } Status;

Status Insert(Node **ppLink,int newValue){//有current版本
    Node *new, *current;

    new = (Node *)malloc(sizeof(Node));
    if(new==NULL){
        return ERROR;
    }
    new->value = newValue;

    while(current=*ppLink,current!=NULL&¤t->valuenext;
    }

    *ppLink = new;
    new->next = current;

    return OK;
}

// Status Insert(Node **ppLink,int newValue){//无*ppLink版本
//     Node *new;

//     new = (Node *)malloc(sizeof(Node));
//     if(new==NULL){
//         return ERROR;
//     }
//     new->value = newValue;

//     while(*ppLink!=NULL&&(*ppLink)->valuenext;
//     }

//     new->next = *ppLink;
//     *ppLink = new;

//     return OK;
// }

int main(int argc,char *argv[]){
    Node *linkedList=NULL;
    int temp;
    srand((unsigned)time(NULL));
    for (int i = 0; i < 10;i++){
        temp = rand() % 101;
        printf("%d ", temp);
        Insert(&linkedList,temp);
    }
    printf("\n");
    for (Node *p = linkedList; p!= NULL;p=p->next){
        printf("%d ", p->value);
    }
    return 0;
}

qsort()函数排序法

#include
#include
#include


int cmp(const void*a,const void *b){
  return *(int *)a - *(int *)b;
}

int main(int argc,char *argv[]){
  int a[50];
  srand((unsigned)time(NULL));
  for (int i = 0; i < 50;i++){
    a[i] = rand() % 101;
    printf("%d ", a[i]);
  }
  printf("\n");
  qsort(a, 50, sizeof(int), cmp);
  for (int i = 0; i < 50;i++){
    printf("%d ", a[i]);
  }
  return 0;
}

你可能感兴趣的:(各种排序方法)