简体   繁体   中英

Dynamic Array in order printing

I need to print an array of in order of largest to smallest. For simplicity, we'll say that it is an array of ints.

The only way I can think to do it is loop through the array, find the largest element, print it and set a corresponding boolean flag so it doesn't get printed twice. Is there a better way to go about this?

int *array;

// Fill array, malloc, all that good stuff

int i, j, max = 0, max_index = 0;
int isPrinted[ARRAY_SIZE] = {0};

for (i = 0; i < ARRAY_SIZE; i++) {
  for (j = 0; j < ARRAY_SIZE; j++) {
    if (isPrinted[j] == 0 && array[j] > max) {
      max = array[j];
      max_index = j;
    }  
  }
  isPrinted[max_index] = 1;
  printf("%d", max);
  max = 0;
}

Yes..sort the array before printing and then print it. If you can't modify the original array, copy the elements to another inserting them in the correct order and print the second one.

Can't you sort the array and then print it ? Or copy the array, sort the copy and print it ? The complexity will be dramatically better (O(n log(n)) instead of O(n ** 2) with your algorithm).

Sort it, then print it. For integers it's possible to do this in linear time. With standard qsort it's O(n*log(n)) .

// stdlib.h
void qsort( void *buf, size_t num, size_t size, int (*compare)(const void *, const void *) ); 

I think you should preferably go for a sort algorithm that reorder your array the way you want. Then print the content of your array sequentially.

如果可以更改元素的顺序,则可以在打印之前在数组上使用排序算法。

As others have pointed out, it's generally more efficient to sort the data first.

Rather than completely sorting the data, however, you can put the data into a priority queue, and print items as your remove them from the priority queue. Although it's not a huge difference (by any means), this does reduce work slightly compared to completely sorting the data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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