數組的插入、刪除以及排序的實現

來源:互聯網
上載者:User

數組的插入:

#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;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.