Common sorting - Java implementation

package struct;

/**
 *
 * @Author: dyy
 * @Company: Shaanxi University of Science and Technology
 * @modified date:
 * @Email: [email protected]
 * @Description: Java implements several common sorting
 */


//select sort class
class SelectSort{
	public void selectSort(int[] arr){
		for(int i = 0;i < arr.length; i++){
			int currentMax = i;//Record the current maximum subscript
			for(int j = i + 1;j < arr.length;j++){
				//find the maximum subscript
				if(arr[j] > arr[currentMax]){
					currentMax = j;
				}
			}
			int temp = arr[i];
			arr[i] = arr[currentMax];
			arr[currentMax] = temp;
		}
	}
	public void print(int[] arr){
		for(int i = 0;i<arr.length;i++){
			System.out.print(arr[i]+" ");
		}
	}
}


// bubble sort class
class BubbleSort{
	    //implementation of bubble sort
		public void bubbleSort(int[] arr){
			for(int i = 0;i < arr.length - 1;i++){
				for(int j = 0;j < arr.length - 1 - i;j++){
					if(arr[j] < arr[j+1]){
						int temp = arr[j];
						arr[j] = arr[j+1];
						arr[j+1] = temp;
					}
				}
			}
		}
		// print the array
		public void print(int[] a){
			for(int i =0 ;i<a.length;i++){
				System.out.print(a[i]+" ");
			}
		}
}


//insertion sort
class InsertSort{
	public void insertSort(int[] arr){
		for(int i = 0; i < arr.length - 1;i++){
			// treat the first element as sorted
			int j;
			int insert = arr[i];
			for(j = i;j > 0 && insert>arr[j-1];j--){
				arr[j] = arr[j-1];
			}
			arr[j] = insert;
		}
	}
	
	// print the array
			public void print(int[] a){
				for(int i =0 ;i<a.length;i++){
					System.out.print(a[i]+" ");
				}
			}
}
 
 
public class TestVeriousSort {
	public static void main(String[] args) {
		int[] arr1 = {13,2,6,34,1,4,9,7,5};
		//selection sort
		System.out.println("Select Sort"+"\n");
		SelectSort obj = new SelectSort();
		System.out.println("Initial array:");
		obj.print(arr1);
		System.out.println("\n"+"sorted array:");
		obj.selectSort(arr1);
		obj.print(arr1);
		
		//Bubble Sort
		System.out.println("\n"+"bubble sort"+"\n");
		BubbleSort obj1 = new BubbleSort();
		System.out.println("Initial array:");
		obj1.print(arr1);
		System.out.println("\n"+"sorted array:");
		obj1.bubbleSort(arr1);
		obj1.print(arr1);
		
		//insertion sort
		System.out.println("\n"+"bubble sort"+"\n");
		InsertSort obj2 = new InsertSort();
		System.out.println("Initial array:");
		obj2.print(arr1);
		System.out.println("\n"+"sorted array:");
		obj2.insertSort(arr1);
		obj2.print(arr1);
	}
}
To be continued.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325986662&siteId=291194637