string array sorting problems

Source: Internet
Author: User
Tags strcmp

Creates an array of strings, a total of 5 elements, each of which holds up to 30 characters, and writes a function to sort the entire array. Method One: #include  <stdio.h> #include  <string.h>void sort (char *arr[], int  n) { char *tmp; int i, j, k; for  (i = 0; i  < n - 1; i++)                    //Select Sort  {  k = i;  for  (j =  i + 1; j < n; j++)   {   if  (strcmp (Arr[k] ,  arr[j]) >0)    {    k = j;   }   }  tmp = arr[i];  arr[i] = arr[k];  arr[k] = tmp;  }}void print (char *arr[], int n) { int i = 0; for  (i  = 0; i < n; i++)  {  printf ("%s\n",  arr[i]);  }}int main () { int n = 5; char *arr[] = {  "ABCDE",   "Efghi",  "HIJKL",  "Bcdef",  "Defgh"  }; sort (arr, n);  print (arr, n );  return 0;} Method Two: #include  <stdio.h> #include  <string.h>int main () { char arr[5][30]  = {  "AAAA",  "CCCC",  "bbbb",  "eeee",  "dddd"  }; int i =  0, j = 0; char tmp[30] = { 0 }; for  (i =  0; i < 4; i++)                            //Bubble Sort  {   for  (j = 0; j < 4 - i; j++)   {    if  (strcmp (arr[j], arr[j + 1])  > 0)    {     strcpy (Tmp, arr[j]);     strcpy (arr[j], arr[j + 1]);     strcpy (arr[j + 1], tmp);   }  } } for  (i  = 0; i < 5; i++)  {  printf ("%s\n",  arr[i]); }  return 0;}


string array sorting problems

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.