bubble sort


See On Github

Data

Contributor

Generic placeholder thumbnail

by pravsingh

in java

Source Code

package github_contributions;

/**
 * 
 * @author pravsingh
 * 
 */
public class bubble_sort {

	/**
	 * Sorts an integer array in ascending order.
	 * 
	 * @param data
	 *            - reference to the integer array to sort, must not be null
	 *            Postcondition: The array is sorted in ascending order.
	 */
	public static void bubbleSort(int[] data) {

		for (int k = 0; k < data.length - 1; k++) {
			boolean isSorted = true;

			for (int i = 1; i < data.length - k; i++) {
				if (data[i] < data[i - 1]) {
					int tempVariable = data[i];
					data[i] = data[i - 1];
					data[i - 1] = tempVariable;

					isSorted = false;

				}
			}

			if (isSorted)
				break;
		}
	}

}
package github_contributions;

import static org.junit.Assert.*;
import org.junit.Test;

/**
 * 
 * @author pravsingh
 * 
 *         Junit test cases around bubble sort.
 * 
 */
public class bubble_sort_unittest {

	@Test
	public void testHappyPath() {

		int data[] = { 1, 3, 2 };
		bubble_sort.bubbleSort(data);

		assertEquals(data[0], 1);
		assertEquals(data[1], 2);
		assertEquals(data[2], 3);
	}

	@Test
	public void testEmptyArray() {

		int data[] = {};
		bubble_sort.bubbleSort(data);

		assertEquals(data.length, 0);
	}

}