Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BubbleSort.java #100

Open
My-1437 opened this issue Jun 14, 2023 · 2 comments
Open

BubbleSort.java #100

My-1437 opened this issue Jun 14, 2023 · 2 comments

Comments

@My-1437
Copy link

My-1437 commented Jun 14, 2023

No description provided.

@Nagaraj-M-K
Copy link

public class BubbleSort {

public static void main(String[] args) {
    int[] array = {64, 34, 25, 12, 22, 11, 90};
    
    System.out.println("Original array:");
    printArray(array);

    // Measure the time taken by bubbleSort
    long startTime = System.currentTimeMillis();
    bubbleSort(array);
    long endTime = System.currentTimeMillis();

    System.out.println("\nSorted array:");
    printArray(array);

    System.out.println("Time taken by Bubble Sort: " + (endTime - startTime) + " milliseconds");
}

// Function to perform Bubble Sort
static void bubbleSort(int[] arr) {
    int n = arr.length;
    for (int i = 0; i < n-1; i++) {
        for (int j = 0; j < n-i-1; j++) {
            if (arr[j] > arr[j+1]) {
                // Swap arr[j] and arr[j+1]
                int temp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = temp;
            }
        }
    }
}

// Function to print an array
static void printArray(int[] arr) {
    for (int i = 0; i < arr.length; i++) {
        System.out.print(arr[i] + " ");
    }
    System.out.println();
}

}

@a123-dev
Copy link

public class BubbleSort {

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

public static void main(String[] args) {
    int[] array = {5, 4, 3, 2, 1};
    System.out.println("排序前的数组:");
    for (int num : array) {
        System.out.print(num + " ");
    }

    bubbleSort(array);

    System.out.println("\n排序后的数组:");
    for (int num : array) {
        System.out.print(num + " ");
    }
}

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants