排序交替最小的大值的数组 [英] Sorting an array with alternate smallest-largest values

查看:173
本文介绍了排序交替最小的大值的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定的阵列我给它以这样的方式,第一元件是最小的值,第二个元素是最大排序需要,第三元件是所述第二最小元素等

但我的code只是打印原始数组,我无法找出原因。任何意见将是AP preciated。

 的#include<&stdio.h中GT;
无效掉期(INT男,INT N);
诠释的main()
{
    INT I,J,A [10],N;    的printf(请输入数组元素\\ n的数量);
    scanf函数(%d个,&安培; N);    对于(i = 0; I< N;我++){
       scanf函数(%d个,&安培; A [I]);
    }
    对于(i = 0; I< N;我++){        如果(ⅰ%2 == 0){
            为(J = I; J< N; J ++){
                如果(A [J]< A [I]){
                    掉期(A [I],A [J]);
                }
            }
        }
        否则如果(ⅰ%2!= 0){
            为(J = I; J< N; J ++){
                如果(A [J]>一种由[i]){
                    掉期(A [I],A [J]);
                }
            }
        }    }    对于(i = 0; I< N;我++){
        的printf(%d个\\ N,A [I]);
    }
    返回0;
}无效掉期(INT男,INT N)
{
    INT温度;
    TEMP =米;
    M = N;
    N =温度;
}


解决方案

您需要使用引用指针传递。

 无效掉期(INT * M,诠释* N)
{
    INT温度;
    TEMP = *米;
    * M = * N;
    * N =温度;
}

和改变你的code来称呼它。

 交换(安培; A [I],和放大器; A [J]);

对于不使用指针,你可以使用这样一个宏的解决方案;

 的#define互换(X,Y){做INT T =(X)(X)=(Y);(Y)= T;}而(0);掉期(A [I],A [J]);

就在你的文件的顶部定义此并删除交换功能和原型。这是所有关于范围,因为宏只是一个的文本替换它在正确的范围内使用[1]。

Given an array I am required to sort it in such a way that the first element is the smallest value, the second element is the largest, the third element is the second smallest element and so on.

But my code just prints the original array and I am not able to figure out why. Any advice would be appreciated.

#include <stdio.h>
void swap(int m, int n);
int main()
{
    int i,j,A[10],n;

    printf ("enter the number of array elements\n");
    scanf ("%d", &n);

    for (i=0;i<n;i++){
       scanf ("%d", &A[i]);
    }


    for (i=0;i<n;i++){

        if (i%2 == 0){
            for (j=i;j<n;j++){
                if (A[j] < A[i]){
                    swap(A[i],A[j]);
                }
            }
        }
        else if (i%2 != 0){
            for (j=i;j<n;j++){
                if (A[j] > A[i]){
                    swap (A[i],A[j]);
                }
            }
        }

    }

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

void swap( int m, int n)
{
    int temp;
    temp = m;
    m = n;
    n = temp;
}

解决方案

You need to pass by reference using pointers.

void swap( int *m, int *n)
{
    int temp;
    temp = *m;
    *m = *n;
    *n = temp;
}

and change your code to call it like this

swap (&A[i],&A[j]);

For a solution that doesn't use pointers you can use a MACRO like this;

#define swap(x,y) do{int t=(x);(x)=(y);(y)=t;}while(0);

swap(A[i],A[j]);

Just define this at the top of your file and remove the swap function and prototype. It's all about scope, because the MACRO is just a text replace it's in the correct scope to use A[i].

这篇关于排序交替最小的大值的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆