冒泡法排序

// 对赋值后的数组进行从大到小的排序,冒泡法排序
//有6个元素需要冒泡法排序的话,外层循环需要6-1次,分别是1,2,3,4,5次;
// 内层循环也需要6-1次,分别是5,4,3,2,1次,从大到小和从小到大任意
#include <stdio.h>
#define N 8

int main()
{
  int arrayorder[N] = { 0 };
  int i = 0, j = 0, t = 0;
  for (i = 0; i < N; ++i)
  {
    printf("请输入元素%d的值arrayorder[%d]=", i, i);
    scanf_s("%d", &arrayorder[i]);
  }
  printf("刚刚输入的数组如下:\n");
  for (i = 0; i < N; ++i)
  {
    printf("arrayorder[%d]=%d\n", i, arrayorder[i]);
  }
  for (i = N-1; i >= 1; --i)
  {
    for (j = 0; j <= i-1; ++j)
    {
      //if (arrayorder[j] < arrayorder[j+1]) //由大到小排,[0]最大
      //{
      // t = arrayorder[j] ;
      // arrayorder[j] = arrayorder[j+1];
      // arrayorder[j+1] = t ;
      //}
      if (arrayorder[j] > arrayorder[j + 1]) //由小到大排,[0]最小
      {
        t = arrayorder[j];
        arrayorder[j] = arrayorder[j + 1];
        arrayorder[j + 1] = t;
      }
    }
  }
  printf("排序后的数组元素为:\n");
  for (i = 0; i < N; ++i)
  {
    printf("arrayorder[%d]=%4d\n", i, arrayorder[i]);
  }
  return 0;
}

 

posted @ 2020-03-01 21:49  代码争霸  阅读(153)  评论(0编辑  收藏  举报