Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Algorithms in Java. Part 1

Sponsored · Ship Features Fearlessly Turn features on and off without deploys. Used by thousands of Ruby developers. →
Victor
August 21, 2016

Algorithms in Java. Part 1

Victor

August 21, 2016

Transcript

53 slides
  1. «… хороший алгоритм позволяет значительно экономить ресурсы, вплоть до того,

    что становится возможным выполнять задачи, которые иначе были бы недоступны»
  2. • Задача о нулевых парах • Оценка времени и памяти

    • Классические алгоритмы сортировки и поиска • Оптимальная реализация задачи о нулевых парах
  3. 1 20 34 4 -1 43 8 … 1 20

    34 4 -1 43 8 … 1 20 34 4 -1 43 8 … 1 20 34 4 -1 43 8 … …
  4. 1 20 34 4 -1 43 8 … …и так

    далее для всех n
  5. public static int count(int a[]) {
 int n = a.length;


    int cnt = 0;
 for (int i = 0; i < n; i++) {
 for (int j = i + 1; j < n; j++) {
 if (a[i] + a[j] == 0) {
 cnt++;
 }
 }
 }
 return cnt;
 } Brute-forсe
  6. • Задача о нулевых парах • Оценка времени и памяти

    • Классические алгоритмы сортировки и поиска • Правильная реализация задачи о нулевых парах
  7. int [ ] ~ 24 + 4N байтов 16 байт

    заголовка объекта 4 байта длина 4 байта дополнительно 4 * N элементов int
  8. public static int count(int a[]) {
 int n = a.length;


    int cnt = 0;
 for (int i = 0; i < n; i++) {
 for (int j = i + 1; j < n; j++) {
 if (a[i] + a[j] == 0) {
 cnt++;
 }
 }
 }
 return cnt;
 } Brute-forсe
  9. public static int count(int a[]) {
 int n = a.length;


    int cnt = 0;
 for (int i = 0; i < n; i++) {
 for (int j = i + 1; j < n; j++) {
 if (a[i] + a[j] == 0) {
 cnt++;
 }
 }
 }
 return cnt;
 } Brute-forсe
  10. 1 20 34 4 -1 43 8 … … 1

    20 34 4 -1 43 8 … N - 1 N - 2 1 1 20 34 … N-1 N
  11. (N - 1) + (N - 2) + … +

    1 = (N - 1)N / 2 O(N2)
  12. • Задача о нулевых парах • Оценка времени и памяти

    • Классические алгоритмы сортировки и поиска • Оптимальная реализация задачи о нулевых парах
  13. public static int count(int a[]) {
 int n = a.length;


    int cnt = 0;
 for (int i = 0; i < n; i++) {
 for (int j = i + 1; j < n; j++) {
 if (a[i] == - a[j]) {
 cnt++;
 }
 }
 }
 return cnt;
 } Brute-forсe
  14. public static int binarySearch(int[] mas, int x) {
 int low

    = 0;
 int high = mas.length - 1;
 int mid;
 
 while (low <= high) {
 mid = (low + high) / 2;
 if (mas[mid] < x) {
 low = mid + 1;
 } else if (mas[mid] > x) {
 high = mid - 1;
 } else {
 return mid;
 }
 }
 //элемент не нашли:
 return -1;
 }
  15. public static int[] bubbleSort(int[] mas) {
 boolean isSorted = false;


    int n = mas.length;
 while (!isSorted) {
 isSorted = true;
 
 for (int i = 0; i < n - 1; i++) {
 if (mas[i] > mas[i + 1]) {
 isSorted = false;
 swap(mas, i, i + 1);
 }
 }
 n = n - 1;
 }
 return mas;
 }
  16. public static void quickSort(int[] array, int left, int right) {


    if (left >= right) {
 return;
 }
 int index = partition(array, left, right);
 quickSort(array, left, index - 1);
 quickSort(array, index + 1, right);
 }
 
 private static int partition(int[] array, int left, int right) {
 // Левый и правый индексы просмотра
 int i = left, j = right + 1;
 // Опорный элемент
 int v = array[left];
 // Просмотр справа, просмотр слева, проверка на завершение и обмен
 while (true) {
 while (array[++i] < v) {
 if (i == right) {
 break;
 }
 }
 while (v < array[--j]) {
 if (j == left) {
 break;
 }
 }
 if (i >= j) {
 break;
 }
 swap(array, i, j);
 }
 swap(array, left, j);
 return j;
 }
 }
  17. • Задача о нулевых парах • Оценка времени и памяти

    • Классические алгоритмы сортировки и поиска • Оптимальная реализация задачи о нулевых парах
  18. public static int сount(int a[]) {
 int n = a.length;


    int cnt = 0;
 Arrays.sort(a);
 for (int i = 0; i < n; i++) {
 //> i для того, чтобы не считать дважды
 if (Arrays.binarySearch(a, -a[i]) > i) {
 cnt++;
 }
 }
 return cnt;
 }
  19. • Алгоритмы и структуры данных JDK: https://habrahabr.ru/post/182776/ • Сортировки в

    JAVA: http://www.javaspecialist.ru/2012/02/java.html • Введение в анализ сложности алгоритмов: https://habrahabr.ru/post/195996/

More Decks by Victor

Other Decks in Programming