-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertionSort.java
More file actions
74 lines (53 loc) · 1.87 KB
/
InsertionSort.java
File metadata and controls
74 lines (53 loc) · 1.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import java.util.Scanner;
import java.util.Arrays;
public class InsertionSort {
public static float[] sortArray( float array[], int order ) {
int countArray = array.length;
for( int i = 1; i < countArray; i++ ) {
float temp = array[ i ];
int j = i - 1;
if ( order == 1 ) { //*FROM THE LOWEST TO THE HIGHEST
while( ( j >= 0 ) && ( array[ j ] > temp ) ) {
array[ j + 1 ] = array[ j ];
j--;
}
} else if ( order == 2 ) { //*FROM THE HIGHEST TO THE LOWEST
while( ( j >= 0 ) && ( array[ j ] < temp ) ) {
array[ j + 1 ] = array[ j ];
j--;
}
}
array[ j + 1 ] = temp;
}
return( array );
}
public static float[] receiveArrayValues() {
Scanner input = new Scanner( System.in );
//Array Size
System.out.print( "Cantidad de números a ser ordenados: " );
int arraySize = input.nextInt();
float[] array = new float[ arraySize ];
//Array Values
System.out.println( "Valores:" );
for( int i = 0; i < arraySize; i++ ) {
System.out.print( " Valor para la posición '" + i + "' del array: " );
array[ i ] = input.nextFloat();
}
return( array );
}
public static void main( String[] args ) {
System.out.println( "--INSERTION SORT--\n\n" );
float[] array = receiveArrayValues();
System.out.println( "\nEl array a ser ordenado es: " );
System.out.println( Arrays.toString( array ) );
Scanner input = new Scanner( System.in );
System.out.println( "\n¿Cómo deseas organizarlo?" );
System.out.println( " 1. Menor a mayor" );
System.out.println( " 2. Mayor a menor" );
System.out.print( "Escoge tu opción: " );
int order = input.nextInt();
array = sortArray( array, order );
System.out.println( "\nEl array ordenado es: " );
System.out.println( Arrays.toString( array ) );
}
}