Programming Algorithm-code (c) Grouping arrays into the smallest number)

Source: Internet
Author: User
Code the smallest number of arrays (c)


Address: http://blog.csdn.net/caroline_wendy


Question: enter a positive integer array, splice all the numbers in the array into a number, and print the smallest of all the numbers that can be concatenated.


Large NumberConvertString, Heavy loadQuick sortingOfComparison Method.


Code:

/* * main.cpp * *  Created on: 2014.6.12 *      Author: Spike *//*eclipse cdt, gcc 4.8.1*/#include <stdio.h>#include <stdlib.h>#include <string.h>int compare(const void* strNumber1, const void* strNumber2) {const int MaxNumberLength = 10;char* strCombine1 = new char[MaxNumberLength*2 + 1];char* strCombine2 = new char[MaxNumberLength*2 + 1];strcpy(strCombine1, *(const char**)strNumber1);strcat(strCombine1, *(const char**)strNumber2);strcpy(strCombine2, *(const char**)strNumber2);strcat(strCombine2, *(const char**)strNumber1);int result = strcmp(strCombine1, strCombine2);delete[] strCombine1;delete[] strCombine2;return result;}void PrintMinNumber (int* numbers, int length) {const int MaxNumberLength = 10;if (numbers == NULL || length <= 0)return;char** strNumbers = (char**)(new int[length]);for (int i=0; i<length; ++i) {strNumbers[i] = new char[MaxNumberLength + 1];sprintf(strNumbers[i], "%d", numbers[i]);}qsort(strNumbers, length, sizeof(char*), compare);for (int i=0; i<length; ++i)printf("%s", strNumbers[i]);printf("\n");for (int i=0; i<length; ++i)delete[] strNumbers[i];delete[] strNumbers;}int main(void){    int input[] =  {3, 32, 321};    PrintMinNumber(input, 3);    return 0;}


Output:

321323





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.