import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main {
public static void main(String[] args) {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyModel myArrayClass = new MyModel(25);
MyView panel = new MyView(myArrayClass);
myArrayClass.myView = panel;
JButton sortButton = new JButton("Sort");
sortButton.addActionListener(e -> performSorting(myArrayClass));
f.getContentPane().add(sortButton, BorderLayout.NORTH);
f.getContentPane().add(panel, BorderLayout.CENTER);
f.setSize(400, 400);
f.setVisible(true);
}
static void performSorting( MyModel myArrayClass) {
Thread thread = new Thread(()-> {
myArrayClass.QuickSort(0, myArrayClass.arraySize - 1);
System.out.println("Done");
});
thread.start();
}
}
class MyView extends JPanel {
MyModel myModel;
public MyView(MyModel myArrayClass) {
this.myModel = myArrayClass;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.WHITE);
int size = myModel.arraySize;
int barWidth = getWidth() / size;
for (int i = 0; i < size; i++) {
int value = myModel.myArray[i];
int x = i * barWidth;
int y = getHeight() - value;
g.fillRect(x + 1, y, barWidth - 2, value);
}
}
}
class MyModel {
int myArray[];
int arraySize;
int res;
MyView myView;
public MyModel(int size) {
arraySize = size;
myArray = new int[arraySize];
for (int i = 0; i < arraySize; i++) {
myArray[i] = (int) (Math.random() * 99) + 1;
}
}
public void QuickSort(int Left, int Right) {
if (Right - Left <= 0) {
return;
} else {
int Pivot = myArray[Right];
Partitioning(Left, Right, Pivot);
int PivotValue = res;
QuickSort(Left, PivotValue - 1);
QuickSort(PivotValue + 1, Right);
}
}
public void Partitioning(int Left, int Right, int Pivot) {
int LeftP = Left - 1;
int RightP = Right;
while (true) {
while (LeftP < Right && myArray[++LeftP] < Pivot) {
}
while (RightP > 0 && myArray[--RightP] > Pivot) {
}
if (RightP <= LeftP) {
SwapValues(LeftP, Right);
res = LeftP;
break;
} else {
SwapValues(LeftP, RightP);
break;
}
}
}
private void SwapValues(int LeftP, int RightP) {
int aux = myArray[LeftP];
myArray[LeftP] = myArray[RightP];
myArray[RightP] = aux;
try {
Thread.sleep(150);
} catch (Exception e) {
Thread.currentThread().interrupt();
}
myView.repaint();
}
}