Bubble sorting and two optimization methods

Source: Internet
Author: User

Bubble sort is the most common way of sorting small data, the following is implemented in C language, and its two optimization methods.

The first optimization method is to set a marker bit to mark whether an interchange has occurred, and to end prematurely if no exchange occurs;

The second optimization method is to record the location of the final release swap, as the next trip to the end of the position.


#include <stdio.h>/* * Print array * */void printArray (int arr[], int n) {int i = 0;for (i = 0; i < n; ++i) {printf ("%d ", Arr[i]);} printf ("\ n");}  /* * Bubble Sort * */void bubblesort (int arr[], int n) {int i = 0;int j = 0;int tmp = 0;for (i = 0; i < n; ++i) {for (j = 0; j < n-1-I; ++J) {if (Arr[j] < Arr[j + 1]) {tmp = Arr[j];arr[j] = arr[j + 1];arr[j + 1] = tmp;}}}} /* * Bubble Sort optimization * Set a flag to flag a trip whether the interchange occurred * If no interchange occurs, the array is already ordered * */void bubbleSort1 (int arr[], int n) {int i = 0;int j = 0;int tmp = 0;int flag = 0; for (i = 0; i < n; ++i) {flag = 0;for (j = 0; J < n-1-I; ++j) {if (Arr[j] < Arr[j + 1]) {flag = 1;tmp = Arr[j ];ARR[J] = arr[j + 1];arr[j + 1] = tmp;}} if (flag = = 0) {break;}}} /* * Bubble sort Optimization Two * Use a variable to record the last occurrence of the swap position, after which no exchange has been ordered * so you can use this value as the next comparison end position * */void bubbleSort2 (int arr[], int n) {int i = 0 ; int j = 0;int k = 0;int tmp = 0;int flag = n; for (i = 0; i < flag; ++i) {k = Flag;flag = 0;for (j = 0; j < K; ++j) {if (Arr[j] < Arr[j + 1]) {flag = J;tmp = A RR[J]; Arr[j] = arr[j + 1];arr[j + 1] = tmp;}}}  int main () {int arr[] = {9, 5, 8, 4, 7, 3, 2, 0, 6, 1};p Rintarray (arr), BubbleSort2 (arr.);p Rintarray (arr.); return 0;}




Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Bubble sorting and two optimization methods

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.