java - 在java中使用线程对数组 block 进行排序

标签 java arrays multithreading sorting javafx

所以我需要让我的程序使用线程使用用户选择的特定排序方法(插入/冒泡/快速/选择)对数组的 block 进行排序。然后,在这些线程完成后,创建其他线程,将这些 block 合并回已排序的数组中。

到目前为止,我的代码是一个 GUI,它要求用户从 4 个单选按钮(冒泡、插入、选择、快速)中进行选择,然后让用户选择数组已排序、随机排序或反向排序的位置。然后用户选择数组大小和 block ( block )大小并点击 go,然后对该方法进行排序并将排序后的方法输出到控制台。如何更改代码以使用线程而不是合并 block ? 这是我的代码:

        package sorting;

import java.util.Random;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;

public class sorting extends Application {

    @Override
    public void start(Stage primaryStage) {

        BorderPane rootPane = new BorderPane();
        GridPane gp = new GridPane();
        rootPane.setCenter(gp);
        gp.setVgap(5);
        gp.setHgap(5);
        rootPane.prefWidth(700);
        rootPane.prefHeight(400);
        gp.prefWidth(400);
        gp.prefHeight(400);
        Label sort = new Label(" Sorting Algorithm ");
        RadioButton selection = new RadioButton("selection ");
        RadioButton bubble = new RadioButton("bubble ");
        RadioButton insertion = new RadioButton("insertion");
        RadioButton quick = new RadioButton("Quick ");
        Label inputType = new Label(" Input Type ");
        RadioButton sorted = new RadioButton("Already Sorted ");
        RadioButton reverse = new RadioButton("Reverse ");
        RadioButton random = new RadioButton("Random ");
        Label inputSize = new Label(" Input Size: ");
        TextField inputText = new TextField();

        inputText.setOnAction((ActionEvent inputText1) -> {
            String inputText2 = inputText.getText();
            double inputText3 = Double.parseDouble(inputText2);
            System.out.println(inputText3);
        });
        Label blockSize = new Label(" Block Size: ");
        TextField block = new TextField();

        block.setOnAction((ActionEvent block1) -> {
            String block2 = block.getText();
            double block3 = Double.parseDouble(block2);
            System.out.println(block3);
        });

        Button go = new Button("Go ");
        ToggleGroup tg = new ToggleGroup();

        selection.setToggleGroup(tg);
        selection.setSelected(true);
        bubble.setToggleGroup(tg);
        insertion.setToggleGroup(tg);
        quick.setToggleGroup(tg);
        ToggleGroup tg1 = new ToggleGroup();
        sorted.setToggleGroup(tg1);
        sorted.setSelected(true);
        reverse.setToggleGroup(tg1);
        random.setToggleGroup(tg1);

        gp.add(sort, 0, 0);
        gp.add(selection, 0, 1);
        gp.add(bubble, 0, 2);
        gp.add(insertion, 0, 3);
        gp.add(quick, 0, 4);
        gp.add(inputType, 0, 7);
        gp.add(sorted, 0, 8);
        gp.add(reverse, 0, 9);
        gp.add(random, 0, 10);
        gp.add(inputSize, 0, 12);
        gp.add(inputText, 1, 12);
        gp.add(blockSize, 0, 13);
        gp.add(block, 1, 13);
        gp.add(go, 0, 16);

        go.setOnAction((ActionEvent go1) -> {
            long startTime = System.currentTimeMillis();
            //selection sorted
            if (selection.isSelected() && sorted.isSelected()) {
                int arraySize = Integer.parseInt(inputText.getText());
                int[] array = getSorted(arraySize, true);
                System.out.println("unsorted: ");
                print(array, Integer.parseInt(block.getText()));
                selectionSort(array);
                System.out.println("sorted: ");
                print(array, Integer.parseInt(block.getText()));
                System.out.println("---------------------------------------");

            }//selction sorted reverse
            else if (selection.isSelected() && reverse.isSelected()) {
                int arraySize = Integer.parseInt(inputText.getText());
                int[] array = getSorted(arraySize, true);
                System.out.println("unsorted: ");
                array = getReverse(array);
                print(array, Integer.parseInt(block.getText()));
                selectionSort(array);
                System.out.println("sorted: ");
                print(array, Integer.parseInt(block.getText()));
                System.out.println("---------------------------------------");
            } //selection sorted random
            else if (selection.isSelected() && random.isSelected()) {
                int arraySize = Integer.parseInt(inputText.getText());
                int[] array = getRandom(arraySize);
                System.out.println("unsorted: ");
                print(array, Integer.parseInt(block.getText()));
                selectionSort(array);
                System.out.println("sorted: ");
                print(array, Integer.parseInt(block.getText()));
                System.out.println("---------------------------------------");
            }//quick sort random
            else if (quick.isSelected() && random.isSelected()) {
                int arraySize = Integer.parseInt(inputText.getText());
                int[] array = getRandom(arraySize);
                System.out.println("unsorted: ");
                print(array, Integer.parseInt(block.getText()));
                quickSort(array, 0, array.length - 1);
                System.out.println("sorted: ");
                print(array, Integer.parseInt(block.getText()));
                System.out.println("---------------------------------------");

            }//quick sort sorted
            else if (quick.isSelected() && sorted.isSelected()) {
                int arraySize = Integer.parseInt(inputText.getText());
                int[] array = getSorted(arraySize, true);
                System.out.println("unsorted: ");
                print(array, Integer.parseInt(block.getText()));
                quickSort(array, 0, array.length - 1);
                System.out.println("sorted: ");
                print(array, Integer.parseInt(block.getText()));
                System.out.println("---------------------------------------");
            }//quick reverse sort
            else if (quick.isSelected() && reverse.isSelected()) {
                int arraySize = Integer.parseInt(inputText.getText());
                int[] array = getSorted(arraySize, true);
                array = getReverse(array);
                System.out.println("unsorted: ");
                print(array, Integer.parseInt(block.getText()));
                quickSort(array, 0, array.length - 1);
                System.out.println("sorted: ");
                print(array, Integer.parseInt(block.getText()));
                System.out.println("---------------------------------------");
            }//insertion sorted sort
            else if (insertion.isSelected() && sorted.isSelected()) {
                int arraySize = Integer.parseInt(inputText.getText());
                int[] array = getSorted(arraySize, true);
                System.out.println("unsorted: ");
                print(array, Integer.parseInt(block.getText()));
                insertionSort(array);
                System.out.println("sorted: ");
                print(array, Integer.parseInt(block.getText()));
                System.out.println("---------------------------------------");
            }//insertion random sort
            else if (insertion.isSelected() && random.isSelected()) {
                int arraySize = Integer.parseInt(inputText.getText());
                int[] array = getRandom(arraySize);
                System.out.println("unsorted: ");
                print(array, Integer.parseInt(block.getText()));
                insertionSort(array);
                System.out.println("sorted: ");
                print(array, Integer.parseInt(block.getText()));
                System.out.println("---------------------------------------");
            }//insertion reverse
            else if (insertion.isSelected() && reverse.isSelected()) {
                int arraySize = Integer.parseInt(inputText.getText());
                int[] array = getSorted(arraySize, true);
                array = getReverse(array);
                System.out.println("unsorted: ");
                print(array, Integer.parseInt(block.getText()));
                insertionSort(array);
                System.out.println("sorted: ");
                print(array, Integer.parseInt(block.getText()));
                System.out.println("---------------------------------------");
            }//bubble sort
            else if (bubble.isSelected() && sorted.isSelected()) {
                int arraySize = Integer.parseInt(inputText.getText());
                int[] array = getSorted(arraySize, true);
                System.out.println("unsorted: ");
                print(array, Integer.parseInt(block.getText()));
                bubbleSort(array);
                System.out.println("sorted: ");
                print(array, Integer.parseInt(block.getText()));
                System.out.println("---------------------------------------");
            }//bubble random sort
            else if (bubble.isSelected() && random.isSelected()) {
                int arraySize = Integer.parseInt(inputText.getText());
                int[] array = getRandom(arraySize);
                System.out.println("unsorted: ");
                print(array, Integer.parseInt(block.getText()));
                bubbleSort(array);
                System.out.println("sorted: ");
                print(array, Integer.parseInt(block.getText()));
                System.out.println("---------------------------------------");
            }//bubble reverse sort
            else if (bubble.isSelected() && reverse.isSelected()) {
                int arraySize = Integer.parseInt(inputText.getText());
                int[] array = getSorted(arraySize, true);
                System.out.println("unsorted: ");
                array = getReverse(array);
                print(array, Integer.parseInt(block.getText()));
                bubbleSort(array);
                System.out.println("sorted: ");
                print(array, Integer.parseInt(block.getText()));
                System.out.println("---------------------------------------");
            }
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("Thread Sorted!");
            alert.setHeaderText("Finished");
            long endTime = System.currentTimeMillis();
            long totalTime = endTime - startTime;
            alert.setContentText("Sort completed in " + totalTime + " milliseconds ");
            alert.showAndWait();

        });
        Scene scene = new Scene(rootPane, 500, 350);
        primaryStage.setTitle("Project 4");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {

        launch(args);

    }
//insertion sort

    public static void insertionSort(int array[]) {
        // int loopCount = 0;
        int n = array.length;
        for (int j = 1; j < n; j++) {
            int key = array[j];
            int i = j - 1;
            while ((i > -1) && (array[i] > key)) {
                array[i + 1] = array[i];
                i--;

            }
            array[i + 1] = key;
        }
        //return loopCount;
    }
//quick sort

    int partition(int arr[], int left, int right) {
        int i = left, j = right;
        int tmp;
        int pivot = arr[(left + right) / 2];

        while (i <= j) {
            while (arr[i] < pivot) {
                i++;
            }
            while (arr[j] > pivot) {
                j--;
            }
            if (i <= j) {
                tmp = arr[i];
                arr[i] = arr[j];
                arr[j] = tmp;
                i++;
                j--;
            }
        }

        return i;
    }
//quick sort

    public void quickSort(int arr[], int left, int right) {
        int index = partition(arr, left, right);
        if (left < index - 1) {
            quickSort(arr, left, index - 1);
        }
        if (index < right) {
            quickSort(arr, index, right);
        }
        //return index;
    }
//bubble sort

    public static void bubbleSort(int[] arr) {
        int n = arr.length;
        //  int loopCount = 0;
        int temp = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 1; j < (n - i); j++) {
                if (arr[j - 1] > arr[j]) {
                    temp = arr[j - 1];
                    arr[j - 1] = arr[j];
                    arr[j] = temp;
                }

            }
        }
        //return loopCount;
    }
//selection sort

    public static void selectionSort(int[] arr) {

        for (int i = 0; i < arr.length - 1; i++) {
            int index = i;
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[j] < arr[index]) {
                    index = j;
                }

            }
            int smallerNumber = arr[index];
            arr[index] = arr[i];
            arr[i] = smallerNumber;
        }

    }

    public static int[] getRandom(int size) {
        Random rand = new Random();
        int[] array = new int[size];
        for (int i = 1; i <= size; i++) {
            array[i - 1] = Math.abs(rand.nextInt()) % 100;
        }
        return array;
    }

    public static int[] getSorted(int size, boolean accending) {
        int[] array = new int[size];
        if (accending) {
            for (int i = 1; i <= size; i++) {
                array[i - 1] = i;
            }
        } else {
            for (int i = size; i > 0; i--) {
                array[size - i] = i;
            }
        }
        return array;
    }

    public static int[] getReverse(int[] arrayw) {
        int[] array = new int[arrayw.length];
        for (int i = 0, j = array.length - 1; i < array.length; i++, j--) {
            array[j] = arrayw[i];
        }
        return array;
    }

    public static void print(int[] array, int blockSize) {
        for (int i = 0; i < array.length; i++) {
            System.out.print(" " + array[i]);
            if ((i + 1) % blockSize == 0) {
                System.out.println();
            }
        }
        System.out.println();
    }

}

最佳答案

除了您的具体问题之外,我还将发布一段以并发方式处理数据数组的代码。
在代码中,创建了2个线程。它们中的每一个都作用于阵列的单独部分。每个线程通过 from 和 to 变量读取其数组部分的边界。
代码非常简单,所以我认为不难理解它在做什么。

    package pk1;

    class Work implements Runnable {

        final public int size = 100;
        private int[] a = new int[size];
        public int[] from = new int[2];
        public int[] to = new int[2];

        public void run() {
        int tn = Integer.parseInt(Thread.currentThread().getName());
        for (int k = from[tn]; k <= to[tn]; k++) {
            a[k] = a[k] ^ 2;

            System.out.println("Working on element " + (tn == 1 ? "\t" : "") + k);
            try {
            Thread.sleep(1);
            } catch (InterruptedException e) {
            }
        }
        }

    }

    public class C1 {

        public static void main(String[] args) {

        Work w1 = new Work();

        w1.from[0] = 0;
        w1.to[0] = w1.size / 2 - 1;

        w1.from[1] = w1.size / 2;
        w1.to[1] = w1.size - 1;

        Thread t1 = new Thread(w1, "0");
        Thread t2 = new Thread(w1, "1");
        t1.start();
        t2.start();

        while (t1.isAlive() || t2.isAlive())
            try {
            Thread.sleep(100);
            } catch (InterruptedException e) {
            }

        }

    }

关于java - 在java中使用线程对数组 block 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43429771/

相关文章:

java - 如何将字符串拆分为后缀数组?

arrays - 关于 Delphi/Generic/array 的 : why this doesn't compile?

c# - 使用 C# 和线程删除大量文件和子文件夹

java - 我如何使用一个 Java 程序来监视另一个 Java 程序的输出?

java - ElasticSearch Java API 客户端 - 发送已序列化的数据并避免序列化

java - 并发链接队列使用CAS

java - sql 语法错误,但串联文本在 Datagrip 中运行正常

c++ - 在动态数组中搜索

java - Akka future 指导

java,如何判断一个字符串是否包含特定顺序的子字符串