Last active
August 29, 2015 14:06
-
-
Save IgorKravchenko10/e586ea6bc8e5eaad9dbb to your computer and use it in GitHub Desktop.
Пузырьковая сортировка
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Скорость работы алгоритма не зависит от размерности массива, но очень зависит от расположения его элементов. Чем они более хаотично разбросаны | |
//тем больше нужно времени для его обработки. Обработка массива в тысячу элементов может быть быстрее его обработки из ста элементов. | |
import java.util.*; | |
public class Bubble { | |
static Scanner scan = new Scanner(System.in); | |
public static void main(String[] args) { | |
int n, arrayOfDouble[]; | |
System.out.print("Enter size of array: "); | |
n = scan.nextInt(); | |
arrayOfDouble = new int [n]; | |
for (int i=0; i<arrayOfDouble.length; i++) | |
arrayOfDouble[i] = (int) ( Math.random() * n); | |
System.out.print("Original array: "); | |
for (int i: arrayOfDouble) | |
System.out.print(i + " " ); | |
long startTime = System.nanoTime(); | |
sort(arrayOfDouble); | |
long estimatedTime = System.nanoTime() - startTime; | |
System.out.println(". Time of sort: " + (startTime-estimatedTime ) + " nanosec."); | |
} | |
static void swap (int[] arrayOfDouble, int i, int j) { | |
int k = arrayOfDouble[i]; | |
arrayOfDouble[i] =arrayOfDouble[j]; | |
arrayOfDouble[j] = k; | |
} | |
static void sort(int[] arrayOfDouble){ | |
for(int i = arrayOfDouble.length-1 ; i >= 0 ; i--){ | |
for(int j = 0 ; j < i ; j++){ | |
if( arrayOfDouble[j] > arrayOfDouble[j+1] ) | |
swap(arrayOfDouble, j, j+1); | |
} | |
} | |
System.out.print(". New array: "); | |
for (int i: arrayOfDouble) | |
System.out.print(i + " " ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment