Bubble sort of structures using pointers in C

丶灬走出姿态 提交于 2019-12-04 06:30:17

Consider the following solution for sorting function:

void bubbleSort(cars *x, int size) 
{
    int i, j;
    for (i = 0; i < size-1; i++) 
    {
        for (j = 0; j < size-1-i; j++) 
        {
            if ( x[j].hp > x[j+1].hp ) 
            {
               cars temp = x[j+1];
               x[j+1] = x[j];
               x[j] = temp;
            }
        }
    }
}

The problem was in the data swap part

void bubbleSort(cars *x, int size)
{
        int i, j;
        cars temp;

        for (i=0;i<size-1;i++) {
            for (j = i+1; j < size; j++) {
                if ( (x+i)->hp > (x+j)->hp ) {
                    temp = x[j];
                    x[j] = x[i];
                    x[i] = temp;
                }
            }
        }
}

This is a reply to a comment under this code; it demonstrates that the sort that I suggest swaps less ... :) Here the code:

#include <stdio.h>
#include <string.h>

typedef struct {
    int x;
    int hp;
} cars;

int swaps;

void bubbleSortB(cars *x, int size)
{
        int i, j;
        cars temp;

        for (i=0;i<size-1;i++) {
            for (j = i+1; j < size; j++) {
                if ( (x+i)->hp > (x+j)->hp ) {
                    temp = x[j];
                    x[j] = x[i];
                    x[i] = temp;
                    swaps++;
                }
            }
        }
}

void bubbleSortA(cars *x, int size)
{
    int i, j;
    for (i = 0; i < size-1; i++)
    {
        for (j = 0; j < size-1-i; j++)
        {
            if ( x[j].hp > x[j+1].hp )
            {
               cars temp = x[j+1];
               x[j+1] = x[j];
               x[j] = temp;
               swaps++;
            }
        }
    }
}

int main(void)
{
    int i;

    cars x[10]={ {1,4},{1,8},{1,12},{1,6},{1,5},{1,4},{1,8},{1,12},{1,6},{1,5} };
    cars y[10]={ {1,4},{1,8},{1,12},{1,6},{1,5},{1,4},{1,8},{1,12},{1,6},{1,5} };

    swaps=0;
    bubbleSortA(x,10);
    for(i=0;i<10;i++)
        printf("%d ",x[i].hp);
    printf("- swaps %d\n",swaps);

    swaps=0;
    bubbleSortB(y,10);  //My sort
    for(i=0;i<10;i++)
        printf("%d ",y[i].hp);
    printf("- swaps %d\n",swaps);

}

Use a swap function like this:

#define TYPE <your type>
void swap(TYPE *a, TYPE *b){
        TYPE *temp = (TYPE*)malloc(sizeof(TYPE));
        *temp = *a;
        *a = *b;
        *b = *temp;
        free(temp);
}

Or this one, without malloc:

void swap(TYPE *a, TYPE *b){
        TYPE temp;
        temp = *a;
        *a = *b;
        *b = temp;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!