简体   繁体   English

使用指针对C中的数组进行排序时遇到问题

[英]Trouble using pointers to sort array in C

I'm working on a program for class. 我正在上课的程序。 We are using pointers. 我们正在使用指针。 We had to generate an array with the number of elements being determined by the user (using malloc). 我们必须生成一个数组,其中元素的数量由用户确定(使用malloc)。 I got that part all working. 我把那部分全部工作了。 Second we had to sort the array in descending order. 其次,我们必须按降序对数组进行排序。 I have no clue why I cant get this to work. 我不知道为什么我不能这样做。 This code flips the whole array, so that 3 4 5 12 5 becomes 5 12 5 4 3, but that is not what I want. 这段代码翻转了整个数组,因此3 4 5 12 5变成5 12 5 4 3,但这不是我想要的。 I'm sure it's something small, but for the life of me I cant figure out what I'm doing wrong. 我敢肯定它很小,但是对于我的一生,我无法弄清楚自己在做错什么。

void main()
{
    int *p, *sizearray, *q;
    int i, siz;
    printf("How large do you want the array? Enter a number between 0 and 50\n");
    scanf("%d", &siz);
    if (siz <= 50)
    {
        p = genarr(siz);
        for (i = 0; i <siz; i++)
            printf("%i\n", *(p + i));

        arrsort(p,siz);

        for (i = 0; i <siz; i++)
            printf("%i\n", *(p + i));
    }
    else
        printf("That number was not in the given range");

    while(1);
}




#include "stdafx.h"
#include <time.h>           // required for the time_t structure
#include <stdlib.h>         // Reqwuired for the srand() and rand() functions
#include "ArrEdit.h"

int* genarr(int size)
{
    time_t t;
    int i, m;
    int *sizearr;

    sizearr = (int*)malloc(sizeof(int)*size);
    srand((unsigned)time(&t));

    for (i = 0; i<size; i++)
        *(sizearr + i) = rand() % 50;

    return sizearr;
    free(sizearr);
}


int *arrsort(int*prt, int si)
{
    int k, j;
    int temp;   // holding variable
    for (k = 0; k< (si - 1); k++)    // element to be compared
    for (j = (k + 1); j < si; j++)   // rest of the elements
    {

        swap(&prt[k], &prt[j]);
    }
    return prt;
}

void swap(int *s, int *r)
{
        int pSwap = *r;
        *r = *s;
        *s = pSwap;

}
for (j = (k + 1); j < si; j++)   // rest of the elements
{

    swap(&prt[k], &prt[j]);
}

This should only swap if k > j, so you need an if statement: 仅当k> j时才应该交换,因此您需要一个if语句:

for (j = (k + 1); j < si; j++)   // rest of the elements
{
    if (prt[k] > prt[j])
        swap(&prt[k], &prt[j]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM