Java:

public class BubbleSort {
  private List<Integer> nos;
  
  public BubbleSort(List<Integer> nos) {
	this.nos = nos;
  }
  
  public void sort() {
	if (this.nos == null || this.nos.size() == 0 || this.nos.size() == 1) {
	  return;
	}
	
	int count = this.nos.size();
	
	while (--count >= 1) {
	  for (int i = 0; i < count; ++i) {
		int first = this.nos.get(i);
		int second = this.nos.get(i + 1);
		
		if (first > second) {
		  this.nos.set(i, second);
		  this.nos.set(i + 1, first);
		}
		
	  }
	}
  }
  
  public static void main(String[] args) {
	List<Integer> nos = new ArrayList<Integer>(Arrays.asList(new Integer[] {3, 6, 1, 5, 4, 2}));
	BubbleSort bubbleSort = new BubbleSort(nos);
	bubbleSort.sort();
	System.out.println(nos);
  }
}

Python:

nos = [3, 6, 1, 5, 4, 2]

count = len(nos) - 1

while count >= 1 :
	for i in range(count) :
		first = nos[i]	
		second = nos[i + 1]

		if first > second :
			nos[i], nos[i + 1] = second, first
	
	count = count - 1

print nos
Advertisements