# Count and Rearrange

## The key takeaway from this coding problem:

`For example:If the numbers are 1, 1, 2, 2, 2, 2, 6 and you are given number 2 to count and push it to the front then, the final output would look likeOutput: 2, 2, 2, 2, 1, 1, 6`

## Naive Solution:

`start function searchElementandSwapp(array, array_size, number){     count = 0     initialIndex = 0     /* Get the count of the number and the index where it was first found */     start for (index is 0 to index is less than array_size increment index by 1)          start if(array[index] is equal to number and count = 0)                increment count by 1                set initialIndex as index          end if          start if(array[index] is equal to number and count != 0)                increment count by 1          end if     end for     /* Now swapp the numbers */     start for (index is 0 to index is less than array_size and array[initialIndex] is equal to number increment  by 1)        start if(array[initialIndex] is equal to number and initialIndex is less than array_size)             swapp array[index] and array[initialIndex]             increment initialIndex by 1        end if     end forend searchElementandSwapp`

## Binary Search Method:

`start function searchElement(array, start_index, end_index, number)       start if(end_index is less than 1)           return -1       end if       mid_index = start_index + (end_index - start_index) / 2         start if(array[mid_index] is equal to number)            return mid_index       end if       start if(array[mid_index] is less than number)            searchElement(array, mid_index + 1, end_index, number)       end if       start else            searchElement(array, start_index, mid_index - 1, number)       end elseend searchElement`
`start function countElement(array, array_size, number)     getIndex = searchElement(array, 0, array_size - 1, number)     /* if the element is not present */     start if(getIndex is equal to -1)         return 0     end if          count = 0     leftCountIndex = getIndex     rightCountIndex = getIndex     initialIndex = 0 /* this will let us know the first position where the number was found to swapp it later on */     /* count left side */      start while(leftCountIndex is greater than or equal to 0 and array[leftCountIndex] is equal to number)           increment count by 1           set initialIndex to leftCountIndex           decrement leftCountIndex by 1     end while     /* count right side */     start while(rightCountIndex is less than the array_size and   array[rightCountIndex] is equal to number)           increment count by 1           incrementrightCountIndex by 1     end while     print count      return initialIndexend countElement`

# Analyze:

--

-- Hi, I am Swapnil Kant, an avid programmer, and a full-time learner! One who is highly interested in Algorithm Optimization and Development