Bubble sorting (arrays in C language are automatically converted into pointers as function parameters)

1. Bubble sorting principle

1. Compare adjacent elements. If the first one is larger than the second, swap them two.
2. Do the same work for each pair of adjacent elements, from the first pair at the beginning to the last pair at the end. At this point, the last element should be the largest number.
3. Repeat the above steps for all elements except the last one.
4. Repeat the above steps for fewer and fewer elements each time until there is no pair of numbers to compare.

2. Step demonstration

Take the following five unordered data as an example: 7 15 9 5 2.

First trip: 7 9 5 2 15 The Insert picture description hereprinciple is the same as the first trip:
Second trip: 7 5 2 9 15
Third trip: 5 2 7 9 15
Fourth trip: 2 5 7 9 15

Three, code example

We write a bubble function bubbleSort(), and then call it in the main function.

1. Examples of errors

#include <stdio.h>
void bubbleSort(int arr[]){
    
    
	int size = sizeof(arr) / sizeof(arr[0]);
	for (int bound = 0; bound < size; bound++){
    
    
		for (int cur = size - 1; cur>bound; cur--){
    
    
			if (arr[cur - 1] > arr[cur]){
    
    
				int temp = arr[cur - 1];
				arr[cur - 1] = arr[cur];
				arr[cur] = temp;
			}
		}
	}
}

int main()
{
    
    
	int arr[]= {
    
     7,15,9,5,2};
	bubbleSort(arr);
	for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++){
    
    
		printf("%d ", arr[i]);
	}
	system("pause");
	return 0;
}

Result:
Insert picture description here
Analysis:
We can see that the bubble sort was not successfully implemented. Set breakpoints for debugging, you can see the value of size is 1.
Insert picture description here
Reason: In C language, arrays as function parameters are automatically converted into pointers of the same type.

2. Correct example

#include <stdio.h>
void bubbleSort(int arr[], int size){
    
    
	for (int bound = 0; bound < size; bound++){
    
    
		for (int cur = size - 1; cur>bound; cur--){
    
    
			if (arr[cur - 1] > arr[cur]){
    
    
				int temp = arr[cur - 1];
				arr[cur - 1] = arr[cur];
				arr[cur] = temp;
			}
		}
	}
}

int main()
{
    
    
	int arr[]= {
    
     7,15,9,5,2};
	int size = sizeof(arr) / sizeof(arr[0]);
	bubbleSort(arr, size);
	for (int i = 0; i < size; i++){
    
    
		printf("%d ", arr[i]);
	}
	system("pause");
	return 0;
}

result:
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_34270874/article/details/109455728