Sort: bubble sort

Algorithm steps:

1) Compare adjacent elements. If the first is bigger than the second, exchange them.

2) Do the same for each pair of adjacent elements, from the first pair at the beginning to the last pair at the end. When this is done, the last element will be the maximum number.

3) Repeat the above steps for all elements except the last one.

4) Continue to repeat the above steps every time for fewer and fewer elements, until no one pair of numbers needs to be compared.

 

package com.sort.bubble.service;

import java.util.Comparator;

/**
 * Bubble sort interface class
 * @author huang
 *
 */
public interface BubbleSortService {

	public <T extends Comparable<T>> void sort(T[] list);
	
	public <T> void sort(T[] list, Comparator<T> comparator);
}
package com.sort.bubble.service.impl;

import java.util.Comparator;

import com.sort.bubble.service.BubbleSortService;

/**
 * Bubble sort interface implementation class
 * @author huang
 *
 */
public class BubbleSortServiceImpl implements BubbleSortService {

	@Override
	public <T extends Comparable<T>> void sort(T[] list) {
		if(null != list && list.length > 1) {
			int len = list.length;
			boolean isSwaped = true;
			T temp = null;
			for(int i=0;i<len && isSwaped;i++) {
				isSwaped = false;
				for(int j=0;j<len-i;j++) {
					if(list[j].compareTo(list[j+1]) > 0) {
						temp = list[j];
						list[j] = list[j+1];
						list[j+1] = temp;
						isSwaped = true;
					}
				}
			}
		}
	}


	@Override
	public <T> void sort(T[] list, Comparator<T> comparator) {
		if(null != list && list.length > 1 && null != comparator) {
			int len = list.length;
			T temp = null;
			boolean isSwaped = true;
			for(int i=0;i<len && isSwaped;i++) {
				isSwaped = false;
				for(int j=0;j<len-i;j++) {
					if(comparator.compare(list[j], list[j+1]) > 0) {
						temp = list[j];
						list[j] = list[j+1];
						list[j+1] = temp;
						isSwaped = true;
					}
				}
			}
			
		}
	}

}

Tags: Java

Posted on Fri, 31 Jan 2020 18:08:01 -0500 by wood1e