To rank the array into the smallest number

Source: Internet
Author: User

Title: Enter an array of positive integers, combine all the numbers in the array into a number, and print the smallest of all the numbers that can be stitched together. For example, the input array {3,32,321} prints out the smallest number 321323 that these 3 numbers can be ranked.

Ideas:
For numbers A and B, the result of the arrangement is AB and BA, if AB is less than BA, you should output AB, that is, a is in front of B, that is, a<b. Conversely, if BA is less than AB, that is, B is in front of a, that is, b<a. If AB equals BA, then a=b.

The maximum length of each integer in the array is a const int g_maxnumberlength=10;//two temporary strings, storing two numbers combined, AB, Bachar *g_strcombine1=new char[2*g_ Maxnumberlength+1];char *g_strcombine2=new char[2*g_maxnumberlength+1];//defines a and B comparison rules: If AB&LT;BA, then a<b; if ba< AB, then b<a; if ab=ba, then a=b;int compare (const void *STR1, const void *STR2) {//abstrcpy (g_strcombine1,* (const char * *) str1) ; strcat (g_strcombine1,* (const char * *) str2)//bastrcpy (g_strcombine2,* (const char * *) str2); Strcat (g_strcombine2,* ( const char * *) str1);//Compare return strcmp (G_STRCOMBINE1,G_STRCOMBINE2);} Prints the smallest number of permutations void printminnumber (int *numbers, int length) {if (numbers==null| | length<=0) return;//defines a level two pointer storage array char **strnumber= (char * *) (new int[length]);//The element of each string array creates a new string and copies the integer into the for (int i= 0; i<length; i++) {strnumber[i]=new char[g_maxnumberlength+1];sprintf (Strnumber[i], "%d", Numbers[i]);} Quickly sort by defined rules qsort (strnumber,length,sizeof (char *), compare);//print for (int i=0; i<length; i++) printf ("%s", Strnumber[i]);p rintf ("\ n");//deletefor (int i=0; i<length; i++) delete[] StrnumBer[i];d elete[] strnumber;} 


To rank the array into the smallest number

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.