Sort arrays with pointers using quicksort

怎甘沉沦 提交于 2019-12-02 16:09:25

问题


I'm trying to sort the values in the array "tab" using quicksort, but it isn't working. the main function just set names and salaries for each tab[n]

typedef struct employee Employee;

struct employee{
  char name[81];
  float salary;
};

Employee *tab[10];

void sort(Employee **tab, int begin, int end){
  int p = tab[(begin + end) / 2] , i = end, j = begin;  
  /*p is the pivot*/
  do{
    while(tab[i]->salary < p && i < end) i++; 
    while(tab[j]->salary > p && j > begin) j--; 

    if(i <= j){
      int tmp = tab[i]->salary;
      tab[i]->salary = tab[j]->salary;
      tab[j]->salary = tmp;
      i++; j--;
    }
  }while(i <= j);

  if(begin < j) sort(tab, begin, j);
  if(end > i) sort(tab, i, end);
}

回答1:


Changes noted in comments. This is a descending order sort (as asked in a follow up question).

#include <stdio.h>

typedef struct employee{
    char name[81];
    float salary;
}Employee;

void sort(Employee **tab, int begin, int end){
    float p = tab[(begin + end) / 2]->salary; /* float needed for compare == */
    int i = begin, j = end;
    Employee *tmp;                          /* microsoft is c89 */

    while(i <= j){                      /* using while */
        while(tab[i]->salary > p) i++;  /* >, <= pivot stops scan */
        while(tab[j]->salary < p) j--;  /* <, >= pivot stops scan */
        if(i > j)                       /* using break */
            break;
        tmp = tab[i];
        tab[i] = tab[j];
        tab[j] = tmp;
        i++; j--;
    }

    if(begin < j) sort(tab, begin, j);
    if(end > i) sort(tab, i, end);
}

int main(int argc, char**argv)
{
    Employee tab[] = {{"john", 525.}, {"jack", 520.},
                      {"mary", 537.}, {"jane", 523.},
                      {"joan", 548.}, {"sam",  524.},
                      {"lisa", 527.}, {"ann",  541.},
                      {"tom",  521.}, {"ted",  531.}};
    Employee *ptr[sizeof(tab)/sizeof(tab[0])];
    int i;
    /* create array of pointers */
    for(i = 0; i < (sizeof(tab)/sizeof(tab[0])); i++)
        ptr[i] = &tab[i];
    sort(ptr, 0, sizeof(ptr)/sizeof(ptr[0])-1);
    for(i = 0; i < (sizeof(ptr)/sizeof(ptr[0])); i++)
        printf("%5s %6.2f\n", ptr[i]->name, ptr[i]->salary);
    return 0;
}


来源:https://stackoverflow.com/questions/57750049/sort-arrays-with-pointers-using-quicksort

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