Bubble sort algorithm Principle and Java implementation Code _java

Source: Internet
Author: User

Bubble Sort Method : A record of a small number of keywords is like a bubble stepping up, the key word larger record is like a stone sinking, each trip has one of the largest stones to the bottom.

Algorithmic Nature: (The maximum is the key point, must be put to the last, so the cycle) each time from the first backward scrolling comparison, so that the maximum value of the bottom, the minimum rise one time, the last one forward (that is, the last just determined the maximum value no longer participate in the comparison, the comparison of 1)

Complexity: Time complexity O (N2), Space complexity O (1)

Java source code (requires a date class to run successfully)

Copy Code code as follows:

public static void Bubblesort (date[] days) {
int len = days.length;
Date temp;
for (int i = len-1 i >= 1; i--) {
for (int j = 0; J < i; J + +) {
if (Days[j].compare (Days[j + 1]) > 0) {
temp = days[j + 1];
Days[j + 1] = Days[j];
DAYS[J] = temp;
}
}
}
}
Class Date {
int year, month, day;

Date (int y, int m, int d) {
Year = y;
month = m;
Day = D;
}

public int Compare (date date) {
Return to year > date.year? 1:year < date.year? -1
: Month > Date.month? 1:month < Date.month? -1
: Day > Date.day? 1:day < Date.day? -1:0;
}

public void print () {
SYSTEM.OUT.PRINTLN (Year + "" + month + "" + day);
}
}

Copy Code code as follows:

Package testsortalgorithm;

public class Bubblesort {
public static void Main (string[] args) {
int array[] = {5, 6, 8, 4, 2, 4, 9, 0};
Bubblesort (array);
for (int i = 0; i < Array.Length; i++) {
System.out.println (Array[i]);
}
}

public static void Bubblesort (int array[]) {
int temp;
for (int i = array.length-1 i > 0; i--) {
for (int j = 0; J < i; J + +) {
if (Array[j] > array[j + 1]) {
temp = Array[j];
ARRAY[J] = array[j + 1];
Array[j + 1] = temp;
}
}
}
}
}

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.