数组插入
对于已经排好序的数组, 只需找到新的数应该插入哪个位置, 然后把插入点之后的所有元素向后挪, 腾出位置后插入新的数即可.
注意, 在挪动后面的数时, 应该从最后面那个数开始, 依次向前.
我写的这个程序除了实现了插入功能外, 还利用一个do while循环实现了多次反复操作. 感兴趣的同学可以看一下.
===========数组插入 by claydodo============
对于已经排好序的数组, 只需找到新的数应该插入哪个位置, 然后把插入点之后的所有元素向后挪, 腾出位置后插入新的数即可.
注意, 在挪动后面的数时, 应该从最后面那个数开始, 依次向前.
我写的这个程序除了实现了插入功能外, 还利用一个do while循环实现了多次反复操作. 感兴趣的同学可以看一下.
===========数组插入 by claydodo============
- #include <stdio.h>
- #define MAX_SIZE 256
- int main()
- {
- int array[MAX_SIZE] =
- { 10, 20, 30, 40, 50, 60};
- int now_size=6;
- int i;
- for(i=0;i<now_size;i++)
- printf("%d ", array[i]);
- printf("/n");
- char choice='y';
- do
- {
- //Input a new number
- printf("Please input a number to insert: ");
- int new_num;
- scanf("%d", &new_num);
- //Find out where to insert
- int find_pos;
- for(find_pos=0; find_pos<now_size; find_pos++)
- {
- if(array[find_pos]>new_num)
- break;
- }
- //Move everyone behind the insert position backward
- int j;
- for(j=now_size-1;j>=find_pos; j--)
- array[j+1]=array[j];
- //Put the new number into the array
- array[find_pos]=new_num;
- //Update the array size
- now_size++;
- //Output the result
- for(j=0;j<now_size;j++)
- printf("%d ", array[j]);
- printf("/n");
- //Whether to insert aother number?
- //Take care of the space in " %c".
- printf("Insert another number? (y/n): ");
- scanf(" %c",&choice);
- }
- while( (choice != 'N') && (choice != 'n') && (now_size < MAX_SIZE) );
- return 0;
- }