首页 > 解决方案 > 在数组中添加多个元素

问题描述

#include <stdio.h>
 
int main () {

int []={1,2,3,7,8};    // add element after 3 --> 4,5,6 (condition that i don't know position of 3 in array)


for(int i=0,i<10;i++)
{
    printf("%d\n",n[i]);
}
   return 0;
}

我想要输出 1,2,3,4,5,6,7,8 但请记住以防我不知道数组中 3 或 7 的位置

标签: arraysc

解决方案


#include <stdio.h>

void swap(int *xp, int *yp)
{
    int temp = *xp;
    *xp = *yp;
    *yp = temp;
}
 
// A function to implement bubble sort
// n = len of tab
void bubbleSort(int arr[], int n)
{
   int i, j;
   for (i = 0; i < n-1; i++)     
 
       // Last i elements are already in place  
       for (j = 0; j < n-i-1; j++)
           if (arr[j] > arr[j+1])
              swap(&arr[j], &arr[j+1]);
}


int main()
{
    int len = 10;
    int top_number_count = 3;
    int data[10] = {1, 11, 3, 4, 5, 20, 7, 8, 9, 10};
    int temp[10];
    
    // copy the tab for dont change any value
    
    for (int i = 0; i < len; i++) {
        temp[i] = data[i];
    }
    // sort the new tab
    bubbleSort(temp, len);
    
    // print the top number 
    // top_number_count is the count of max number you want
    for (int i = len - top_number_count; i < len; i++)
        printf(">%d\n", temp[i]);
    
    return 0;
}

推荐阅读