I have achieved this by changing some modifications in Jaimin's code. This is the solution :
$bestcategoryId = 19; // Your category Id
$bestcategory = Mage::getModel('catalog/category')->load($bestcategoryId);
$bestcategory->setPostedProducts(array()); // Removes all old products added to your category
$bestcategory->save();
$_storeId = Mage::app()->getStore()->getId();
$_products = Mage::getResourceModel('reports/product_collection')
->addOrderedQty()
->addAttributeToSelect('*')
->addAttributeToFilter('visibility', array(
Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH,
Mage_Catalog_Model_Product_Visibility::VISIBILITY_IN_SEARCH
))
->setOrder('ordered_qty', 'asc');
$categorybest = array($bestcategoryId);
foreach ($_products as $_product){
$product = Mage::getModel('catalog/product')->load($_product->getId());
$categoryb = array_merge($categorybest,$product->getCategoryIds());
$product->setCategoryIds($categoryb);
$product->save();
}
Thanks for @Jaimin support.