Download code

Jump to: navigation, search

Back to Merge_sort_(C)

Download for Windows: single file, zip

Download for UNIX: single file, zip, tar.gz, tar.bz2

mergesort_array_test.c

 1 /* The authors of this work have released all rights to it and placed it
 2 in the public domain under the Creative Commons CC0 1.0 waiver
 3 (http://creativecommons.org/publicdomain/zero/1.0/).
 4 
 5 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 6 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 7 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 8 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 9 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
10 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12 
13 Retrieved from: http://en.literateprograms.org/Merge_sort_(C)?oldid=17235
14 */
15 
16 #include <string.h>
17 #include <time.h>    /* time() */
18 #include <stdlib.h>  /* rand() */
19 #include <stdio.h>   /* puts() */
20 
21 #define MIN_MERGESORT_LIST_SIZE    32
22 
23 
24 void mergesort_array(int a[], int size, int temp[]) {
25     int i1, i2, tempi;
26     if (size < MIN_MERGESORT_LIST_SIZE) {
27         /* Use insertion sort */
28         int i;
29         for (i=0; i < size; i++) {
30             int j, v = a[i];
31             for (j = i - 1; j >= 0; j--) {
32                if (a[j] <= v) break;
33                 a[j + 1] = a[j];
34             }
35             a[j + 1] = v;
36         }
37         return;
38     }
39     mergesort_array(a, size/2, temp);
40     mergesort_array(a + size/2, size - size/2, temp);
41     i1 = 0;
42     i2 = size/2;
43     tempi = 0;
44     while (i1 < size/2 && i2 < size) {
45         if (a[i1] <= a[i2]) {
46             temp[tempi] = a[i1];
47             i1++;
48         } else {
49             temp[tempi] = a[i2];
50             i2++;
51         }
52         tempi++;
53     }
54     while (i1 < size/2) {
55         temp[tempi] = a[i1];
56         i1++;
57         tempi++;
58     }
59     while (i2 < size) {
60         temp[tempi] = a[i2];
61         i2++;
62         tempi++;
63     }
64     memcpy(a, temp, size*sizeof(int));
65 }
66 
67 int main(int argc, char* argv[]) {
68     int size = atoi(argv[1]);
69     int* a    = malloc(sizeof(int)*size);
70     int* temp = malloc(sizeof(int)*size);
71     int i;
72     srand(time(NULL));
73     for(i=0; i<size; i++) {
74         a[i] = rand() % size;
75     }
76     mergesort_array(a, size, temp);
77     for(i=1; i<size; i++) {
78         if (!(a[i-1] <= a[i])) {
79             puts("ERROR");
80             return -1;
81         }
82     }
83     puts("SUCCESS");
84     return 0;
85 }


hijacker
hijacker
hijacker
hijacker