-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.java
More file actions
97 lines (82 loc) · 3.25 KB
/
App.java
File metadata and controls
97 lines (82 loc) · 3.25 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class App {
public static void main(String[] args) {
//creating the frame
JFrame frame = new JFrame("Sorting Application");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.setResizable(false);
//create input label
JLabel inputLabel = new JLabel("Enter Number (Comma Seperated) :");
inputLabel.setBounds(10, 10, 200, 25);
frame.add(inputLabel);
// create input text field for user
JTextField inputField = new JTextField();
inputField.setBounds(10, 40, 360, 28);
frame.add(inputField);
//create Sort button
JButton sortButton = new JButton("Sort");
sortButton.setBounds(10, 80, 80, 28);
frame.add(sortButton);
// Create output section
JTextField outputField = new JTextField();
outputField.setBounds(10, 150, 360, 25);
outputField.setEditable(false);
frame.add(outputField);
// Add action listner to the button
sortButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String inputText = inputField.getText();
if (inputText.isEmpty()) {
JOptionPane.showMessageDialog(frame,"Please enter some numbers.");
return;
}
//collect input text by commas and convert to an integer array
String[] stringNumbers = inputText.split(",");
int[] numbers = new int[stringNumbers.length];
try {
for (int i = 0; i < stringNumbers.length; i++){
numbers[i] = Integer.parseInt(stringNumbers[i].trim());
}
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(frame, "Please enter valid integer");
return;
}
//Sort the array using selection sort
selectionSort(numbers);
// convert sorted array to string and set into th output
StringBuilder sortedNumbers = new StringBuilder();
for (int i = 0; i < numbers.length; i++){
sortedNumbers.append(numbers[i]);
if (i < numbers.length -1) {
sortedNumbers.append(", ");
}
}
outputField.setText(sortedNumbers.toString());
}
});
// set visible
frame.setVisible(true);
}
public static void selectionSort(int[] array){
for (int i = 0; i < array.length - 1; i++){
int minIndex = i;
for (int j = i + 1; j < array.length; j++){
if (array[j] < array[minIndex]) {
minIndex = j;
}
}
int temp = array[minIndex];
array[minIndex] = array[i];
array[i] = temp;
}
}
}