# Thread: Program where the user can choose the algorithm

1. Member
Join Date
Feb 2009
Posts
5
Rep Power
0

## Program where the user can choose the algorithm

Hi,

I'm trying to make a code where the user can choose a sorting method: Bubble, Insertion or Shell. It doesn't work. Could anyone help?
Here it is:

import javax.swing.*;
import java.text.*;
import java.lang.*;

class SortingMethods {
public static void main(String[] args){
String numberStr;
int number;
int array[]= {10,97,6,23,0,-45,697, -1000, 1, 0};
int i;
System.out.println("This application asks for the selection of one of three sorting methods.");
numberStr= JOptionPane.showInputDialog(null,"Enter number 1) for Insertion, 2) for Shell, or

3) for Bubble ");
number= Integer.parseInt(numberStr);

insertionSort(array, array.length);
shellSort(array, array.length);
bubbleSort(array, array.length);

for(i=0; i<array.length; i++) {
System.out.print(array[i] + " " );
}
}

private static void insertionSort ( int data[],int n) {
int array[]= {10,97,6,23,0,-45,697, -1000, 1, 0};
int number= 0;
int tmp,i,j;
if( number== 1) {
for(j=1;j<n; j++) {
i=j-1;
tmp = data[j];
while ((i>=0)&& (tmp< data[i]) ) {
data[i+1]= data[i];
i--;
}
data[i+1]= tmp;
insertionSort(array, array.length);
System.out.println("The list of the organized numbers is:");
}
}
}
public static void shellSort(int[] a, int n) {
int array[]= {10,97,6,23,0,-45,697, -1000, 1, 0};
int number=0;

if( number==2) {
int increment= a.length / 2;
while (increment > 0) {
for( int i=increment; i< a.length; i++) {
int j = i;
int temp = a[i];
while(j>= increment && a[j- increment]>temp){
a[j]= a[j- increment];
j-= increment;
}
a[j]= temp;
}
if(increment==2) {
increment=1;
} else{
increment *= (5.0/11);

}

}
shellSort(array, array.length);
System.out.println("The organized list is:");
}
}
private static void bubbleSort(int[] array, int length) {
//int array[]= {10,97,6,23,0,-45,697, -1000, 1, 0};
int temp, j, i;
int number=0;
if(number==3) {
for(i=1; i<length; i++) {
for(j=0; j<length-i; j++) {
if(array[j]> array[j+1]) {
temp= array[j];
array[j]= array[j+1];
array[j+1]= temp;
bubbleSort(array, array.length);
System.out.println("The organized numbers list is:");
}
}
}
}
}
}

2. Member
Join Date
Feb 2009
Posts
96
Rep Power
0
In your code you are not checking user input.Use enums or switch-case statements,like
//
switch(numberstr)
case1 :For insertion
----
break;
case2 : For Bubble
--
break;
case3 :For shell
---
break;

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•