Note: This website is archived. For up-to-date information about D projects and development, please visit wiki.dlang.org.
Version 4 (modified by garth, 14 years ago)
Last example with foreach did not modify the array (only local assignment of variables).

BubbleSort

Description

Simple BubbleSort class implementation that sorts a static array

Example

import std.stdio;

/**
*	BubbleSort implementation in D
**/
class BubbleSort {
	
	int[]	tobsorted;
	public:
	
	/**
	* Constructor
	**/
	this(int[] array) {
		tobsorted			= array;
	}
	
	int[] sort() {
		// initialize variables
		// x+y are used to iterate through the array using a for-loop
		int	x, y, temp;

		// Iterate through every element in array
		for(x = 0; x < tobsorted.length; x++) {

			// 2nd iteration through array, comparing elements with each other
			// y may not be equal or bigger than array.length (throws exception)
			
			for(y=0; y < (tobsorted.length -1); y++) {

				// comare elements to each other
				// If element y < x
				// swap elements
				if(tobsorted[x]	< tobsorted[y]) {

					temp		= tobsorted[x];
					tobsorted[x]	= tobsorted[y];
					tobsorted[y]	= temp;
				}
			}

			// Output current array to console
			foreach(int i; tobsorted) {
				writef("%02d ",i);
			}

			// append newline
			writefln();
		}

		// return sorted array
		return tobsorted;
	}
}


/** Explains itself
*   Initialize int-array with 15 elements
*	Then calls BubbleSort and outputs the sorted array	
**/ 
int main(char[][] args) {
	
	// initialize array

	static int[]	array	= [15,4,3,14,2,5,1,8,7,19,15,13,9,12,6,11];

	writefln("BubbleSort in D");
	writefln("---------------");
	writef("Sorting following numbers:\t");
	foreach(int i; array) {
		writef("%02d ",i);
	}
	writefln("\nStarting now...");
	writefln();

	BubbleSort	s	= new BubbleSort(array);
	array			= s.sort();

	writefln();
	writefln("I finished!");
	writef("Here's your sorted array:\t");
	foreach(int i; array) {
		writef("%02d ",i);
	}

	return 0;
}