SORTING ARRAY ELEMENTS


public class SortArray {

/*
* idea of sort
* select largest element and swap others
*/
public static void selectionSort(double array[]) {

for (int i = array.length - 1; i >= 1; i--) {
//index of element
int index = 0;

//cuurent num i compare two number set one of them as max
double currentMaxElement = array[0];

// loop to determine largest element
for (int j = 1; j <= i; j++) {
if (currentMaxElement < array[j]) {
// max element equal max num
currentMaxElement = array[j];
index = j;
}//end of if
}//end of second for

//check to swap element
if (index != i) {
array[index] = array[i];
array[i] = currentMaxElement;
}//end of if
}//end of for

}//end of selection method

//begin main method
public static void main(String[] args) {

//define an object
SortArray obj = new SortArray();

//array to test method
double testArray[] = {3, 2, 1, 4, 8, 6, 9, 0};

//call method to sort array
obj.selectionSort(testArray);
//call method to print element
obj.printElement(testArray);

}//end of main

//define method to loop and print element of array
//pass array to method
public static void printElement(double arr[]) {
for (int i = 0; i < arr.length; i++) {
System.out.println(i + ":" + "'" + arr[i] + "'");
}//end of for

}// end of print method
}//end of class

Advertisements

One thought on “SORTING ARRAY ELEMENTS

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s