PartMC
2.2.1
|
00001 /* Copyright (C) 2011 Matthew West 00002 * Licensed under the GNU General Public License version 2 or (at your 00003 * option) any later version. See the file COPYING for details. 00004 */ 00005 00006 /** \file 00007 * \brief Wrapper routines for C qsort. 00008 */ 00009 00010 #include <stdlib.h> 00011 00012 /** \brief Helper function for integer_sort_c() 00013 */ 00014 int pair_compare(const void *a, const void *b) 00015 { 00016 int a_val = *((int*)a); 00017 int b_val = *((int*)b); 00018 00019 if (a_val < b_val) { 00020 return -1; 00021 } else if (a_val > b_val) { 00022 return 1; 00023 } else { 00024 return 0; 00025 } 00026 } 00027 00028 /** \brief Sort the given data array and return the permutation. 00029 * 00030 * On return the \c data array is sorted and the \c perm array 00031 * contains the permutation, so that <tt>new_data[i] = 00032 * data[perm[i]]</tt>, where \c data is the original data and \c 00033 * new_data is the sorted data. 00034 * 00035 * \param n The length of \c data and \c perm. 00036 * \param data The data array (sorted on return). 00037 * \param perm The permutation on return: <tt>new_data[i] = 00038 * data[perm[i]]</tt>. 00039 */ 00040 int integer_sort_c(int n, int *data, int *perm) 00041 { 00042 int *data_perm; 00043 int i; 00044 00045 data_perm = (int*)malloc(sizeof(int) * 2 * n); 00046 for (i = 0; i < n; i++) { 00047 data_perm[2 * i] = data[i]; 00048 data_perm[2 * i + 1] = i + 1; 00049 } 00050 qsort(data_perm, n, 2 * sizeof(int), pair_compare); 00051 for (i = 0; i < n; i++) { 00052 data[i] = data_perm[2 * i]; 00053 perm[i] = data_perm[2 * i + 1]; 00054 } 00055 free(data_perm); 00056 }