Skip to content

Instantly share code, notes, and snippets.

@Dakasha26
Last active June 29, 2021 13:02
Show Gist options
  • Save Dakasha26/efba386929d29e0cf96eb30b6854a100 to your computer and use it in GitHub Desktop.
Save Dakasha26/efba386929d29e0cf96eb30b6854a100 to your computer and use it in GitHub Desktop.
Algorithms. Daniil Skvortsov. 2 variants of the solution
package program;
public class CocktailSort {
public static void cocktailSort(int[] array) {
int temp;
int left = 0;
int right = array.length - 1;
do {
for(int i = left; i < right; i++) {
if(array[i] > array[i + 1]) {
temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
}
}
right -= 1;
for(int i = right; i > left; i--) {
if(array[i] < array[i - 1]) {
temp = array[i];
array[i] = array[i - 1];
array[i - 1] = temp;
}
}
left += 1;
} while(left < right);
}
}
package program;
public class Program {
public static int firstSolution(int[] array){
CocktailSort.cocktailSort(array);
int firstEl = array[0];
for(int i = 1; i < array.length; i++)
if(firstEl == array[i])
return firstEl;
else
firstEl = array[i];
return -1; // Не может быть по условию задачи
}
// Алгоритм "черепахи и зайца" Флойда
public static int secondSolution(int[] array){
int tort = array[0];
int hare = array[0];
while(true){
tort = array[tort];
hare = array[array[hare]];
if(tort == hare)
break;
}
int point1 = array[0];
int point2 = tort;
while(point1 != point2){
point1 = array[point1];
point2 = array[point2];
}
return point1;
}
public static void main(String[] args) {
int[] array = {1,3,4,3,4}; // Пользовательский ввод данных не реализован, чтобы не загромождать код
int ans1 = firstSolution(array);
int ans2 = secondSolution(array);
System.out.println(ans1);
System.out.println(ans2);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment