2016-02-10 151 views
-3

我是C新手,並且遇到此代碼的一些問題。基於另一個陣列順序的數組排序

我需要將數組拆分爲兩個不同的數組,並按第一個數組的順序對第二個數組進行排序。

有什麼想法嗎?

下面是我走到這一步:

#include <stdio.h> 
void main() 
{ 
    int currentN; 
    int i, n; 
    int array[20]; 
    printf("Enter the value of n\n"); 
    scanf("%d", &n); 

    if (n%2 !=0) 
    { 
    printf("sequence would not be equ. please enter Odd \n"); 
    printf("Please Enter even number\n"); 
    scanf("%d", &n); 
    } 
    //add 
    printf("enter the numbers\n"); 

    for (i = 0; i < n; ++i) 
    { 
    scanf("%d", &array[i]); 
    // scanf("%d", &currentN); 
    // seq[i]= currentN; 
    } 
    n++; 
    //add 
    int *firstHalf = malloc(n/2 * sizeof(int)); 
    if (!firstHalf) 
    { 
    /* handle error */ 
    } 

    int *secondHalf = malloc(n/2 * sizeof(int)); 
    if (!secondHalf) 
    { 
    /* handle error */ 
    } 

    memcpy(firstHalf, array, n/2 * sizeof(int)); 
    memcpy(secondHalf, array + n/2, n/2 * sizeof(int)); 

    for (i = 0; i < n/2; i++) 
    { 
    printf("%d\t", firstHalf[i]); 
    //printf("%d\n", secondHalf[i]); 
    //printf("\n************************"); 
    } 
    printf("\n*********************\n"); 
    for (i = 0; i < n/2; i++) 
    { 
    printf("%d\t", secondHalf[i]); 
    } 
} 
+0

你說的「問題」究竟是什麼? –

+0

我想按照第一個數組順序對第二個數組進行排序 – Joh

+0

@Joh請在[如何接受答案工作?](http://meta.stackexchange.com/q/5234/179419)上看到此帖子。 –

回答

0

一種方式來獲得你所需要的:

  1. 創建一個struct有兩個成員。
  2. 創建一個struct的數組。
  3. 填充struct數組,使原始數組的前半部分存儲在struct數組元素的第一個成員中,原始數組的第二部分存儲在struct數組元素的第二個成員中。使用元素的第一個元素排序struct數組。
0

你最後memcpy功能後僅僅添加以下代碼:

int j, temp; 
for(i = 0; i < n/2; i++) 
{ 
for(j = 0; j < n/2 - 1; j++) 
{ 
    if(firstHalf[j] > firstHalf[j+1]) 
    { 
    temp = firstHalf[j]; 
    firstHalf[j] = firstHalf[j+1]; 
    firstHalf[j+1] = temp; 

    temp = secondHalf[j]; 
    secondHalf[j] = secondHalf[j+1]; 
    secondHalf[j+1] = temp; 
    } 
} 
} 

我已經使用基本冒泡排序,但你可以使用任何的高級排序算法。

訣竅是,在進行比較時只需要使用firstHalf數組,但在交換時,可以交換兩個數組中的元素。

+0

謝謝!這很有幫助! – Joh

+0

樂於幫忙,歡迎來到Stack Overflow。如果此答案或任何其他人解決了您的問題,請將其標記爲已接受。 –

相關問題