Data structure and algorithms-bubble sort (Java implementation)

Source: Internet
Author: User

[TOC]

Bubble Sort Program code
Package Com.uplooking.bigdata.datastructure;import Java.util.arrays;public class Bubblesort {public static void main (S        Tring[] args) {int[] arr = {8,-2, 3, 9, 0, 1, 7, 6};        System.out.println ("Before sorting:" + arrays.tostring (arr));        Bubblesort (arr);    System.out.println ("After sorting:" + arrays.tostring (arr)); /** * Sorting Process Analysis: * I previous comparison (Arr.length is 8) * Start: 8,-2, 3, 9, 0,           1, 7, 6 * * End of 1th trip:-2, 3, 8, 0, 1, 7, 6, 9 0 7 * * 2nd trip ended:-2, 3, 0, 1, 7, 6, 8, 9 1     6 * * End of 3rd trip:-2, 0, 1, 3, 6, 7, 8, 9 2 5 * * 4th trip Ends:-2, 0, 1, 3, 6, 7, 8, 9 3 4     * * End of 5th trip:-2, 0, 1, 3, 6, 7, 8, 9 4 3 * * 6th trip Ends:-2, 0, 1, 3, 6, 7, 8, 9 5 2 * * End of 7th trip:-2, 0, 1, 3, 6, 7, 8, 9 6 1 * * Conclusion: The number of trips to compare is arr.length-1 * Each trip needs to be compared Arr.len Gth-1-I times * * Because the bubble sort is reversed for each other, and does not change the order of its original sort, so it is stableSorting method */public static void Bubblesort (int[] arr) {for (int i = 0; i < arr.length-1; i++) {fo  R (Int j = 0; J < arr.length-1-I; j + +) {if (Arr[j] > arr[j + 1]) {swap (arr, J,                j + 1);        }}}} public static void Swap (int[] arr, int i, int j) {Arr[i] = Arr[i] ^ arr[j];        ARR[J] = Arr[i] ^ arr[j];    Arr[i] = Arr[i] ^ arr[j]; }}
Test
排序前:[8, -2, 3, 9, 0, 1, 7, 6]排序后:[-2, 0, 1, 3, 6, 7, 8, 9]
Analysis of time complexity
1.可以看到,将比较次数相加起来(等差数列),其时间复杂度为O(n^2)2.由于冒泡排序为相邻两者相互比较对调,并不会更改其原本排序的顺序,所以是稳定排序法

Data structure and algorithms-bubble sort (Java implementation)

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.