数组插入

来源:互联网 发布:流程图软件visio2016 编辑:程序博客网 时间:2024/05/29 15:19
数组插入

对于已经排好序的数组, 只需找到新的数应该插入哪个位置, 然后把插入点之后的所有元素向后挪, 腾出位置后插入新的数即可.

注意, 在挪动后面的数时, 应该从最后面那个数开始, 依次向前.

我写的这个程序除了实现了插入功能外, 还利用一个do while循环实现了多次反复操作. 感兴趣的同学可以看一下.

===========数组插入 by claydodo============
  1. #include <stdio.h>
  2. #define MAX_SIZE 256
  3. int main()
  4. {
  5.     int array[MAX_SIZE] =
  6.         { 10, 20, 30, 40, 50, 60};
  7.     int now_size=6;
  8.     int i;
  9.     for(i=0;i<now_size;i++)
  10.       printf("%d ", array[i]);
  11.     printf("/n");
  12.     char choice='y';
  13.     do
  14.     {
  15.         //Input a new number
  16.         printf("Please input a number to insert: ");
  17.         int new_num;   
  18.         scanf("%d", &new_num);
  19.        
  20.         //Find out where to insert
  21.         int find_pos;
  22.         for(find_pos=0; find_pos<now_size; find_pos++)
  23.         {
  24.             if(array[find_pos]>new_num)
  25.               break;
  26.         }
  27.        
  28.         //Move everyone behind the insert position backward
  29.         int j;
  30.         for(j=now_size-1;j>=find_pos; j--)
  31.           array[j+1]=array[j];
  32.         //Put the new number into the array
  33.         array[find_pos]=new_num;
  34.         //Update the array size
  35.         now_size++;
  36.         //Output the result
  37.         for(j=0;j<now_size;j++)
  38.           printf("%d ", array[j]);
  39.         printf("/n");
  40.         //Whether to insert aother number?
  41.         //Take care of the space in " %c".
  42.         printf("Insert another number? (y/n): ");
  43.         scanf(" %c",&choice);
  44.     }
  45.     while( (choice != 'N') && (choice != 'n') && (now_size < MAX_SIZE) );
  46.     return 0;
  47. }

原创粉丝点击