Searching and Sorting

来源:互联网 发布:linux卸载jdk1.5 编辑:程序博客网 时间:2024/05/17 01:19

前言

在逆向cm时, 看到人家排序用到了qsort.
从来没用过…, 做个试验.

记录

// test1958.cpp : Defines the entry point for the console application.// Searching and Sorting - qsort#include "stdafx.h"#include <windows.h>/* QSORT.C: This program reads the command-line * parameters and uses qsort to sort them. It * then displays the sorted arguments. */#include <stdlib.h>#include <string.h>#include <stdio.h>int compare1(const void* arg1, const void* arg2);void testcase1();int compare2(const void* arg1, const void* arg2);void testcase2();int main(int argc, char* argv[]){    // testcase1();    testcase2();    system("pause");    return 0;}void testcase2(){    int i = 0;    int iAry[6] = {        1,        2,        3,        4,        5,        6,    };    /* Output original list: */    for (i = 0; i < (sizeof(iAry) / sizeof(iAry[0])); ++i) {        printf("%d ", iAry[i]);    }    printf("\n");    /* Eliminate argv[0] from sort: */    /* Sort remaining args using Quicksort algorithm: */    qsort((void*)iAry, (size_t)(sizeof(iAry) / sizeof(iAry[0])), sizeof(iAry[0]), compare2);    /* Output sorted list: */    for (i = 0; i < (sizeof(iAry) / sizeof(iAry[0])); ++i) {        printf("%d ", iAry[i]);    }    printf("\n");}int compare2(const void* argR, const void* argL){    // argL为list靠左边的数据    // argr为list靠右边的数据    // 这里传来的是元素的引用    /* Compare all of both strings: */    int iR = *(int*) argR;    int iL = *(int*) argL;    if (iL > iR) {        return 1;    } else if (iL == iR) {        return 0;    } else {        return -1;    }    /** 送来的数据次序    1,2    1,3    1,4    1,5    1,6    6,2    2,3    2,4    2,5    6,5    5,3    3,4    6,5    5,4    6,5    */    // 1,2,3,4,5,6 => 6,5,4,3,2,1}void testcase1(){    int i = 0;    const char* szMsg[6] = {        "msg6",        "msg5",        "msg4",        "msg3",        "msg2",        "msg1",    };    /* Output original list: */    for (i = 0; i < (sizeof(szMsg) / sizeof(szMsg[0])); ++i) {        printf("%s ", szMsg[i]);    }    printf("\n");    /* Eliminate argv[0] from sort: */    /* Sort remaining args using Quicksort algorithm: */    qsort((void*)szMsg, (size_t)(sizeof(szMsg) / sizeof(szMsg[0])), sizeof(szMsg[0]), compare1);    /* Output sorted list: */    for (i = 0; i < (sizeof(szMsg) / sizeof(szMsg[0])); ++i) {        printf("%s ", szMsg[i]);    }    printf("\n");}int compare1(const void* arg1, const void* arg2){    // 这里传来的是元素的引用    /* Compare all of both strings: */    return _stricmp(* (char**) arg1, * (char**) arg2);}
0 0
原创粉丝点击