Sorting algorithm is important on programming, so we will discuss about the simplest algorithm that is  Selection Sort.

Basic algorithm “Selection Sort” is looking the smallest number in the data and exchange it with element in the first position, then find the second smallest element and exchange it with the element in the second position, and continue in this way until whole data is sorted.

Selection Sort Function :

public int[] SelectionSort(int[] mySorting){
	int myDataLong = mySorting.length;
	int i,j,temp;	

	for (i=0; i< mySorting[temp]){
				temp = j;
			}
		}
		if (i != temp) {
			int swap = mySorting[i];
			mySorting[i] = mySorting[temp];
			mySorting[temp] = swap;
		}
	}
	return mySorting;
}

Full source code :

public class SelectionSort{

	public int[] myArray = new int [5];

	public void initData(){
		myArray[0]=30;
		myArray[1]=56;
		myArray[2]=43;
		myArray[3]=12;
		myArray[4]=84;
	}	

	public int[] SelectionSort(int[] mySorting){
		int myDataLong = mySorting.length;
		int i,j,temp;	

		for (i=0; i< mySorting[temp]){
					temp = j;
				}
			}
			if (i != temp) {
				int swap = mySorting[i];
				mySorting[i] = mySorting[temp];
				mySorting[temp] = swap;
			}
		}
		return mySorting;
	}

	public static void main (String args[]){

		SortingDemo sd = new SortingDemo();
		sd.initData();

		int[] myData = sd.myArray;
		int i, myDataLong = myData.length;

		System.out.println("\nBefore Sorting");
		for(i=0;i<myDataLong;i++){
                    System.out.print(myData[i]+" ");
                }

                //Calling Selection Sort Method
                sd.SelectionSort(myData);

                System.out.println("\nAfter Sorting with Selection Sort");
                for(i=0;i<myDataLong;i++){
                    System.out.print(myData[i]+" ");
                }
                System.out.println("");
       }
}

So, Keep Bandung Beautiful Lah….

Advertisements