C language: thinking about string sorting algorithm

Claim:

  • According to the first character of the string, sort the
    student tree new bee in the order of az => bee new student tree
  • Use three methods to compare the first letters of two strings:
    1 array judgment
    2 pointer judgment
    3 mixed judgment

Public part :

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main()
{
	char* arr[] = { "cshdf", "ehsdhf", "bjhdjfhd","abee" };
	bubble(arr, 4);
	for (int i = 0; i < 4; i++)
	{
		printf("%s\n", arr[i]);
	}
	system("pause");
	return EXIT_SUCCESS;
}

Function section

Array judgment:

void bubble(char ** arr,int len)
{
	for (int i = 0; i < len - 1; i++)
	{
		for (int j = 0; j < len - i - 1; j++)
		{
		if (arr[j][0] > arr[j+1][0])
			{
				char * temp = arr[j];
				arr[j] = arr[j+1];
				arr[j + 1] = temp;
			}
		}

Pointer judgment :

void bubble(char ** arr,int len)
{
	for (int i = 0; i < len - 1; i++)
	{
		for (int j = 0; j < len - i - 1; j++)
		{
		if (**(arr + j) < **(arr + j + 1))
			{
				char * temp = *(arr+j);
				*(arr + j) = *(arr + j + 1);
				*(arr + j + 1) = temp;
			}
		}

Mixed judgment:

void bubble(char ** arr,int len)
{
	for (int i = 0; i < len - 1; i++)
	{
		for (int j = 0; j < len - i - 1; j++)
		{
		if (*arr[j] > *arr[j + 1])
			{
				char * temp = arr[j];
				arr[j] = arr[j+1];
				arr[j + 1] = temp;
			}
		}

Code analysis:

First understand how to compare strings? Nothing more than compare stringsASCII value of the first letterSize, then we can easily think of the bubble sorting algorithm of the integer array we learned, the process is: character => ASCLL => bubble

Array judgment:

char* arr[] = { "cshdf", "ehsdhf", "bjhdjfhd","abee" };

It can be regarded as a two-dimensional array. For example: arr [0] [0] = c;
Insert picture description herepointer judgment :

Insert picture description hereMixed judgment:
Insert picture description here

Published 28 original articles · Liked7 · Visits1170

Guess you like

Origin blog.csdn.net/haduwi/article/details/105455045