Commit b27c4ba2 authored by Huynh-Dan VO's avatar Huynh-Dan VO

Count

parents
Pipeline #1739 skipped
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package countoccurrences;
/**
*
* @author Dan
*/
public class CountOccurrences {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int[] numbers={1,2,1,2,3,41,1,1,1,1,1,2,2,3,4,5,5,5,5,5,6,6};
int k = 2;
QuickSort(numbers, 0, numbers.length-1);
/*for (int i=0;i<numbers.length;++i)
{
System.out.println(numbers[i]+" ");
}
*/
System.out.println("The number of "+k+" in the array is: "+ Count(k,numbers,0,numbers.length-1));
}
public static void QuickSort(int[] array, int left, int right)
{
int i = left, j = right;
int temp;
int mid = (left+right)/2;
int pivot = array[mid];
while(i<=j)
{
while(array[i]<pivot)
++i;
while(array[j]>pivot)
--j;
if(i<=j){
temp = array[i];
array[i] = array[j];
array[j] = temp;
++i;
--j;
}
}
if(left<j)
QuickSort(array, left, j);
if(i<right)
QuickSort(array, i, right);
}
public static int Count(int k, int[] numbers, int startIndex, int endIndex)
{
if(endIndex < startIndex)
return 0;
if(numbers[startIndex] > k)
return 0;
if(numbers[endIndex] < k)
return 0;
if(numbers[startIndex]==k && numbers[endIndex]==k)
return endIndex-startIndex+1;
int midIndex = (startIndex + endIndex)/2;
if(numbers[midIndex]==k)
return 1 + Count(k,numbers,startIndex,midIndex-1)+Count(k,numbers,midIndex+1,endIndex);
else if(numbers[midIndex]>k)
return Count(k,numbers,startIndex,midIndex-1);
else if(numbers[midIndex]<k)
return Count(k,numbers,midIndex+1,endIndex);
return 0;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment