当前所在位置:珠峰网资料 >> 计算机 >> 计算机等级考试 >> 正文
C数组的插入与删除以及排序
发布时间:2010/8/4 10:32:48 来源:城市学习网 编辑:ziteng
  数组的插入:
  #include <stdio.h>
  #define SIZE 10
  int main()
  {
  int a[SIZE]={10,12,14,16,18,20,13,200,134,59}; /* 初始化数组 */
  int b[SIZE+1]={0},i,j,x,v; /* b数组为插入后的数组,新插入了一个元素,所以要在原数组的基础上加1 */
  printf(\"Please input insert addr:\");
  scanf(\"%d\",&x); /* 插入值的位置 */
  printf(\"Please input insert value:\");
  scanf(\"%d\",&v); /* 插入值 */
  for (i=0;i<=SIZE-1;i++) {
  if (i==x) { /* 循环数组a,当数组a元素值的位置与插入值的位置相等时 */
  b[i]=v; /* 把插入值赋给数组与数组a元素值相等的位置i */
  b[i+1]=a[i]; /* 把原来数组a中i位置的值赋下一个位置 */
  }
  if (i>x) b[i+1]=a[i]; /* 当循环中的i大于插入值的位置x时,以后每一个元素所放的位置向后退一
  格 */
  if (i<x) b[i]=a[i]; /* 当循环中的i小于插入值的位置x时,每一个元素所放的位置不变 */
  }
  printf(\"This array is:n\");
  for (j=0;j<=SIZE;j++)
  printf(\"%5d\",b[j]); /* 打印数组 */
  printf(\"n\");
  return 0;
  }
  数组的删除:
  #include <stdio.h>
  #define SIZE 10
  int main()
  {
  int a[SIZE]={10,12,14,16,18,20,13,200,134,59};
  int b[SIZE-1]={0},i,j,x,v;
  printf(\"Please input insert addr:\");
  scanf(\"%d\",&x);
  for (i=0;i<=SIZE-1;i++) {
  if (i==x) b[i-1]=a[i];
  if (i>x) b[i-1]=a[i];
  if (i<x) b[i]=a[i];
  }
  printf(\"This array is:n\");
  for (j=0;j<=SIZE-2;j++)
  printf(\"%5d\",b[j]);
  printf(\"n\");
  return 0;
  }
  数组的插入跟数组删除大体上差不多,当插入元素后,插入点后面的每一个元素向后移一个位置,而删除是向前移一个位置。
  数组的排序(泡沫排序法):
  /* 本程序把数组的值按升排列 */
  #include <stdio.h>
  #define SIZE 15
  main()
  {
  int a[SIZE]={900,2,3,58,34,76,32,43,56,70,35,234,532,543,2500};
  int i,pass,hold,j=0,k=0;
  printf(\"Data items in oraginal ordern\");
  for (i=0;i<=SIZE-1;i++) /* 打印排序前的数组 */
  printf(\"%6d\",a[i]);
  for (pass=1;pass<=SIZE-1;pass++) { /* 比较的趟数 */
  for (i=0;i<=SIZE-(pass+1);i++) { /* 比较一趟,注意这里的条件是SIZE-(pass+1) */
  if (a[i]>a[i+1]) {
  hold=a[i];
  a[i]=a[i+1];
  a[i+1]=hold;
  }
  }
  }
  printf(\"nData items in ascending ordern\");
  for (i=0;i<=SIZE-1;i++) /* 打印排序后的数组 */
  printf(\"%6d\",a[i]);
  printf(\"n\");
  return 0;
  }
  Come on!
广告合作:400-664-0084 全国热线:400-664-0084
Copyright 2010 - 2017 www.my8848.com 珠峰网 粤ICP备15066211号
珠峰网 版权所有 All Rights Reserved